[英]ReactJs - Child not updating after Parent State changed
我是ReactJS的新手,我遇到状态概念和重新渲染组件的问题。
在我的父组件中,我在构造函数中有这种状态:
this.state = {
locale : 'en',
messages : ENGLISH.messages,
softwareInfo : {
software_name : 'Test Default 1.0',
default_dash : 1,
color_theme: '#009900'
}
}
在Render中,我加载一个名为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}}
/>
);
这工作很好。
不幸的是,父组件进行了一次更改softwareInfo的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获取的新值。
错误在哪里? 更改父状态应更新子项。
谢谢!
问题是你只在子的构造函数中传递父级的状态。 如果父更新道具,您需要执行componentWillReceiveProps并更新子状态或直接使用software_settings
作为prop。
例如,在子组件中:
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});
}
您需要在子组件上设置componentWillReceiveProps
挂钩以更新它。 https://reactjs.org/docs/react-component.html#componentwillreceiveprops
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.