render() 中的 connect()?

connect() within render()?

我有一个动态属性列表,我正试图使用​​它为该列表中的每个对象实例化一个 React 组件。

这是我的 mapStateToProps()mapDispatchToProps() 的简化版本:

export function mapStateToProps(id) {
  return function(state) {
    return state.widgets.find((widget) => id === widget.id);
  };
}

export function mapDispatchToProps(id) {
  return function (dispatch) {
    return {
      fetchData: (path, props) => dispatch(fetchData(id, path, props)),
    };
  }; 
};

然后在父组件中:

render() {

  const widgets = this.props.widgets.map((widget) => {
    return connect(
      mapStateToProps(id),
      mapDispatchToProps(id),
    )(Widget);
  });

  return <div>{ widgets }</div>;
}

它不会抛出任何异常,但不会调用 mapStateToProps()mapDispatchToProps()

到目前为止,我唯一的猜测是 connect() 需要更早调用,但我不确定如何使用动态道具列表来做到这一点。有人对如何使这项工作有任何想法吗?

mapStateToPropsmapDispatchToProps 都有第二个参数 ownProps。您可以在这些函数中获取传递的道具,并像导出任何其他容器一样导出连接的 Widget。

// WidgetContainer.js

function mapStateToProps(state, ownProps) {
  return state.widgets.find((widget) => ownProps.id === widget.id);
}

function mapDispatchToProps(dispatch, ownProps) {   
  return {
    fetchData: (path, props) => dispatch(fetchData(ownProps.id, path, props)),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Widget);

然后在你的循环中执行@thedude 建议的操作:

return <div>{this.props.widgets.map(w => <Widget id={w.id} />)}</div>

文档:https://github.com/reactjs/react-redux/blob/master/docs/api.md

请不要在渲染方法中使用连接。相反,使用道具将您需要的任何内容发送到 children.

@connect(state => ({
  widgets: state.yourReducer.widgets
}), {
  fetchData: yourFetchActionCreator, // <-- bind your action creator here
})
class ParentComponent extends PureComponent {

  render() {
    return (
      <div>
      {
        this.props.widgets.map(widget =>
          <Widget {...widget} fetchData={this.props.fetchData} />)
      }
      </div>
    );
  }
}

Widget 中,您将拥有每个 widget object.

中的 ID 和所有内容

祝你好运!