【问题标题】:ReactJs - Child not updating after Parent State changedReactJs - 父状态更改后子不更新
【发布时间】:2018-07-08 05:23:12
【问题描述】:

我是 ReactJS 的新手,我对状态的概念和组件的重新渲染有疑问。

在我的父组件中,我在构造函数中有这个状态:

this.state = {
        locale : 'en',
        messages : ENGLISH.messages,
        softwareInfo : {
                        software_name : 'Test Default 1.0',
                        default_dash : 1,
                        color_theme: '#009900'
                       }
    }

在渲染中,我加载了一个名为 DashAppBar 的组件,传递了 softwareInfo:

<DashAppBar softwareInfo = { this.state.softwareInfo} />

在 DashAppBar 构造中,我将该状态读取为属性:

this.state = {
       software_settings: props.softwareInfo,
       [...]
}

然后我在栏中打印软件名称:

const software_name = ( 
            <FormattedMessage 
                id="software_name" 
                defaultMessage="{software_name}"
                values={{software_name:this.state.software_settings.software_name}}
            />
        );

这很好。

不幸的是,父组件进行了更改软件信息的 AJAX 调用:

success: function(result){
        //window.software_settings = $.parseJSON(result);
        //window.software_settings = result;
        var settings = {
                          software_name:result.software_name,
                          default_dash:result.default_dash,
                          color_theme:result.color_theme
                       };
        this.setState({softwareInfo : settings});
}

调用 setState 应该重新渲染组件,但子值保持不变,从 AjaxCall 获取的新值不显示。

错误在哪里?更改父状态应该更新子状态。

谢谢!

【问题讨论】:

  • Ajax 调用被正确触发了?
  • 除非您要在子组件中更改该属性,否则不要将其放入State。而是直接从props 阅读。

标签: javascript reactjs


【解决方案1】:

问题是您仅在子构造函数中传递父状态。如果父级更新道具,您要么需要执行componentWillReceiveProps 并更新子状态,要么直接使用software_settings 作为道具。

例如在子组件中:

const software_name = ( 
            <FormattedMessage 
                id="software_name" 
                defaultMessage="{software_name}"
                values={{software_name:this.props.software_settings.software_name}}
            />
        );

componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    this.setState({ software_settings: nextProps.software_settings});
}

【讨论】:

    【解决方案2】:

    你需要在你的子组件上设置一个componentWillReceiveProps 钩子来更新它。 https://reactjs.org/docs/react-component.html#componentwillreceiveprops

    【讨论】:

      猜你喜欢
      • 2016-10-02
      • 2016-09-18
      • 2021-03-31
      • 2019-05-31
      • 1970-01-01
      • 2021-07-17
      • 2021-07-07
      • 2019-07-12
      • 2021-06-08
      相关资源
      最近更新 更多