[英]How to update the state in mounting in reactjs
如何在安装后更新状态或如何在反应中从一页移动到另一页时传递状态。
在 My Scenario 中,通过单击按钮Add New
,它会指向 AddNew 页面,点击save
将重定向到显示页面,这是有效的。 当我移动到添加新页面时,显示多选保持不变(始终为 en),重定向后如何获得呈现状态
class Display extends React.PureComponent{
constructor(props) {
super(props);
}
componentWillMount() {
console.log(this.state.language);
const defLanguage = this.props.loginData.language; // "en"
this.setState({ language: defLanguage.split(",") }, () =>
this.callQueryApiForFetch("ONLOAD")
);
}
render(){
<MultiSelect
filterOptions={formatLanguageArray(
languageConfig.pvalues
)}
setSelectedFieldValues={value => {
this.setState({ language: value }, () => {
this.callQueryApiForFetch("ONLOAD");
});
}}
id="language"
itemsSelected={this.state.language}
label="Select Language"
/>
<button className="page-header-btn icon_btn display-inline">
<img
title="edit"
className="tableImage"
src={`${process.env.PUBLIC_URL}/assets/icons/ic_addstore.svg`}
/>
{`Add New`}
</button>
}
}
class AddNew extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps = () => {
const defLanguage = this.props.location.state.language;
this.setState({ language: defLanguage });
}
render(){
<Link
to={{
pathname: "/ui/product-info",
state: {
language: this.state.language
}
}}
className="btn btn-themes btn-rounded btn-sec link-sec-btn"
>
Save
</Link>
}
既然你提到重定向到下一页,你也可以试试this.props.history.push("/report")
这里“/report”是你想要重定向到的链接。 你可以查看 React-Routing 概念(只是一个建议)
要将道具从父组件发送到子组件您的情况:
componentWillReceiveProps(nextProps){
if(nextProps.someValue!==this.props.someValue){
//Perform some operation
this.setState({someState: someValue });
this.classMethod();
}
}
在 React 中将状态管理与组件渲染逻辑分开是一个很好的做法。 这个想法是你将集中状态的片段从上到下传递给你的组件层次结构,并允许它们在它们的render
方法中使用这些数据。 在这种方法中,您可以避免将应用程序状态保留在组件中。
每当组件需要更改应用程序状态时,它都会分派由名为“reducer”的函数处理的消息,并更新存储中的状态。 整个概念基于对整个应用程序具有单一的真实来源,并防止组件直接操纵存储。
实现这一点的标准方法是使用称为 Redux 的设计模式,它通过react-redux
库提供给 React 应用程序。
我建议您查看本教程,了解如何在实践中使用 React Redux 库。
1. 将 Display 设为 Component 而不是 PureComponent。
2.在Display中定义一个本地状态
// default state..
state = {
language: 'us',
}
3.console 是否在 Display 的道具中获取语言(将安装)。
//可能在里面
this.props.location.state
4.然后设置状态
this.setState(prevState => ({
...prevState,
language: --value--,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.