【问题标题】:Updating React state after Finished Rendering完成渲染后更新 React 状态
【发布时间】:2017-01-01 07:33:24
【问题描述】:

我正在学习 react 的生命周期方法,我想知道如何最好地解决这种情况:

我有一个组件可以获取有关某人的爱好的信息

  componentWillMount() {
    this.props.fetchHobbies(this.props.params.id);
  }

数据被发送到一个reducer,该reducer被映射为组件底部的prop

function mapStateToProps(state) {
  return { 
    hobbies:state.hobbies.user
  };
}

我有一个名为 twitterbootstrap 的组件,它依赖于我的组件的状态来查看选择了哪些行。

const selectRowProp = {
  mode: 'radio',
  clickToSelect: true,
  bgColor: "rgba(139, 195, 74, 0.71)",
  selected: this.state.selected,
};

这是我的问题。我想访问this.props.hobbies.selected

--更新我正在使用 componentWillRecieveProps,因为它有一个 setState 选项。

componentWillReceiveProps(nextProps){
    this.setState({selected:next.props.hobbies })
} 

我想使用 this.props.hobbies.selected 作为下一个要接收的道具。我将如何整合它?

【问题讨论】:

  • 你能用 componentWillReceiveProps 吗?
  • @ioseph 感谢您的提示!我做了一些研究,我认为这是在正确的轨道上。你知道将状态“selected”设置为 this.props.hobbies.selected 的正确语法是什么吗?
  • 已选择:nextProps.hobbies

标签: javascript reactjs components state


【解决方案1】:

nextProps 是第一次渲染后传递的 props 对象。函数 componentWillReceiveProps 中没有任何名为 next.props 的内容。你可以做这样的事情。

componentWillReceiveProps(nextProps){
    this.setState({selected:nextProps.hobbies })
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2022-01-26
    • 2017-03-26
    • 2016-11-04
    • 1970-01-01
    • 2021-05-17
    • 2021-04-24
    • 2022-06-30
    相关资源
    最近更新 更多