【问题标题】:How to pass props (that getting from Redux) from one Component to another (React/Redux)?如何将道具(从 Redux 获取)从一个组件传递到另一个组件(React/Redux)?
【发布时间】:2019-05-17 05:17:09
【问题描述】:

如何将 props(从 Redux 获取)从 WrapperComponent 传递到 InnerComponent(React/Redux)?

import React, { Component } from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import InnerComponent from "./InnerComponent ";

class WrapperComponent extends Component {
  state = {
    data: []
  };

  render() {
    return (
      <div>
        <InnerComponent props={this.props} />
      </div>
    );
  }
}

const mapStateToProps = state => ({
  data: state.data
});

export default connect(mapStateToProps)(withRouter(WrapperComponent));

在渲染 WrapperComponent 之后 - 道具仍然不在。 任何 LifeCicle 方法都无法解决它。

有可能吗?

【问题讨论】:

    标签: reactjs redux react-redux react-router react-router-dom


    【解决方案1】:

    这是可能的,建议这样做,这样您就不需要每次都通过“连接”调用所有的 HOC 存储。将所有相关的操作和减速器调用到您的容器中,并将它们作为道具传递。

    这种情况下,你的reducer名字叫data,你需要这样调用(我把props名字改成data,所以你可以给你的孩子调用props.data):

    <InnerComponent data={this.props.data} />
    

    或者你可以像这样传递父母的所有道具:

    <InnerComponent {...this.props} />
    

    【讨论】:

    • 谢谢!!那么在那种情况下&lt;InnerComponent props={this.props} props - 是我试图通过的新道具吗?
    • 是的,在这种情况下,道具是您称为道具的道具,但您可以给出任何名称。如果你调用 props props,你将不得不调用你的子 props.props。如果你的孩子是一个类,你必须调用 this.props.props,如果是功能组件:props.props。
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多