【问题标题】:Binding Props to State ReactJS将 Props 绑定到状态 ReactJS
【发布时间】:2019-07-13 19:02:45
【问题描述】:

我在互联网上读到执行以下操作是一种糟糕的编码习惯:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      someItem = props.someItem
    };
  }
}

但是,如果我有这种情况:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      someItem = this.props.someItem
    };
  }
}

Test.propTypes = {
  someItem: PropTypes.array
};

function mapStateToProps(state, ownProps) {
  [...]
  return {
    someItem: someItem
  };
}

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

会有问题吗?在网上找不到没有说我不能这样做的任何地方。

我试图确保每次我导航回该组件时,该组件都能够从 Redux Store 获取数据。我尝试使用 componentWillReceiveProps(),但到目前为止它只运行一次并且 c​​omponentDidMount 和 componentWillMount 不接受 setState。

干杯。

【问题讨论】:

  • 直接使用道具即可。为什么要复制到状态? componentWillReceiveProps 也被贬值了。
  • @johnnypeter 我知道,我正在使用 React 15,这就是它仍然可用的原因。如前所述,如果我依赖 componentWillReceiveProps() 方法,它只会运行一次。当我离开并返回页面时,它不会运行,我的本地状态也不会更新。
  • 应该有一个单一的事实来源,无论是 prop 还是 state,如果您想在第一次挂载时使用 props 初始化 state,然后将其留给组件,则可以在构造函数中将 prop 分配给 state
  • 是的,Rahul,但我读过文章说将其初始化为状态并不好。所以我在这里很困惑

标签: javascript reactjs redux state react-props


【解决方案1】:

您不应该将 props 保存在 state 中,除非您想稍后在本地修改它,并在对 props 提供者采取一些行动后对其进行更新。简而言之,您声明在代码中的所有时间点都不能直接从 props 派生。

即使你使用 redux mapStateToProps 为组件提供 props,它仍然与来自父组件相同

class Test extends React.Component {
  render() {
      console.log(this.props.someItem);
  }
}

Test.propTypes = {
  someItem: PropTypes.array
};

function mapStateToProps(state, ownProps) {
  [...]
  return {
    someItem: someItem
  };
}

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

【讨论】:

  • 我需要稍后修改它。另外,如果您参考stackoverflow.com/questions/54778492/redux-store-not-connected/…,您将了解我的问题的上下文。我似乎无法确保我的本地状态正在从商店获取数据,因为 componentWillReceiveProps 只运行一次。
  • componentWillReceiveProps 不会被调用一次,而是在每次渲染父级时以及道具更改时调用
  • 另外请检查这个问题stackoverflow.com/questions/48139281/…
  • 一开始我也是这么想的,但是当我放一个 console.log() 语句时,该语句永远不会被打印出来。因此,当我 setState({someItem: this.props.someItem});我打电话给 console.log(this.state.someItem);在 render() 方法中,它返回一个空白数组。
  • 还有一点需要注意的是,componentWillReceiveProps 不会在初始渲染时触发,因此当您离开该组件并导航回它时,您实际上是在重新安装该组件,因此首先componentDidMountconstructor 被调用。此外,如果您使用 v16.3.0 或能够调用getDerivedStateFromProps
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-11
  • 2020-01-12
相关资源
最近更新 更多