如何使用react-redux连接

Kre*_*eha 4 reactjs redux react-redux

我对connect()有一点问题.我认为包装Provider中的所有组件都会起作用,但事实证明它不是......所以我发现我需要使用react-redux中的connect().问题是我不知道应该如何使用它.这个网站显示了一些例子但是,我没有任何动作创建者进入连接因为我不使用它们.......有人可以给我一些建议吗?我只是想在组件内访问我的商店......

Shu*_*tri 7

为了在您的容器中使用您的商店,您需要做两件事

首先:利用mapStateToProps().顾名思义,它将状态变量从您的商店映射到您指定的道具

其次:您需要将这些连接props到您的容器.这是connect()进入图片的地方.mapStateToProps组件返回的对象连接到容器.你可以从react-reduxlike 导入连接import {connect} from 'react-redux';

import React from 'react';
import { connect } from 'react-redux';

class App extends React.Component {
  render() {
    return <div>{this.props.containerData}</div>;
  }
}

function mapStateToProps(state) {
  return { containerData: state.appData };
}

export default connect(mapStateToProps)(App);
Run Code Online (Sandbox Code Playgroud)


Ben*_*erg 2

阅读此处的Redux 文档,您可能会有更好的运气。

以下是连接功能如何工作的简单示例:

import React from 'react';
import { connect } from 'react-redux';

class Item extends React.Component {
  render() {
    return <div onClick={() => this.props.dispatch( /* some action here */ )}>{this.props.name}</div>;
  }
}

function mapStateToProps(state) {
  return { name: state.name };
}

export default connect(mapStateToProps)(Item);
Run Code Online (Sandbox Code Playgroud)

上面发生的情况是,当您导出Item组件时,您正在导出包装的连接组件。包装组件将从应用程序状态传入 prop (它还会将函数作为 propname传入)。dispatch