【问题标题】:React child component state not updating when new props are passed传递新道具时反应子组件状态不更新
【发布时间】:2018-01-13 16:34:48
【问题描述】:

我正在渲染一个自定义模态组件,该组件根据从父组件传入的道具显示。道具isVisible 最初是false,然后通过按钮在父组件中更新。我正在通过渲染函数中的console.log 语句检查组件状态。当组件第一次初始化时,它会按预期记录false false,但是当更新 isVisible 时,它​​会返回false true。为什么状态没有随着道具更新?

class MyModal extends React.Component {
  constructor(props) {
    super(props);
      this.state = {
        createModalVisible:props.isVisible,
      };

   setCreateModalVisible = (visible) => {
     this.setState({createModalVisible:visible});
   }

   componentWillMount(){
     this.setCreateModalVisible(this.props.isVisible);
   }

  }
  render() {
    console.log(this.state.createModalVisible,this.props.isVisible);

    return (//modal stuff)
  }
}
export default MyModal

我知道这可能是非常基本的组件生命周期内容,但我无法从文档中弄清楚,而且对 React 还很陌生。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    由于 constructorcomponentWillMount 仅在每个安装到 DOM 树中的组件运行一次,因此不会在传递的每个 props 上更新状态。

    this.state 对于每个组件实例都是本地的,需要使用 this.setState() 进行更新才能在每个渲染过程中使用更新的状态对象。

    使用 componentWillReceiveProps,您可以在其中设置状态以反映传入的新道具,以便您获得所需的内容。

    【讨论】:

    • componentWillReceiveProps 已弃用。你应该改用shouldComponentUpdate(nextProps, nextState)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2017-09-10
    • 2021-05-19
    相关资源
    最近更新 更多