[英]How to pass a mutated state to a different page?
In my App.js, I'm creating a Route as such: 在我的App.js中,我正在这样创建一个Route:
<Route
exact path='/tools/ndalink'
render={(props) => (
<React.Fragment>
<Header />
<LinkPage {...props} brokerID={this.state.brokerID}></LinkPage>
</React.Fragment>
)}
/>
state.brokerID is initially "", but changed shortly after, therefore LinkPage receives this.state.brokerID as "". state.brokerID最初为“”,但不久后更改,因此LinkPage将此this.state.brokerID接收为“”。
How can I pass the changed state.brokerID (without using Redux)? 如何传递更改后的state.brokerID(不使用Redux)?
You need to use a lifecycle method to get the props to the component to wait for the props called componentDidUpdate
. 您需要使用生命周期方法来获取组件的道具,以等待名为
componentDidUpdate
的道具。
That being said, you only have to use this if you plan to mutate the brokerId
. 话虽如此,如果您打算突变
brokerId
,则只需要使用它。
Since the process is async you'll have to wait for the props to be passed down. 由于该过程是异步的,因此您必须等待道具传递下去。 Until the you can show a
loading
text or progess bar. 直到您可以显示正在
loading
文本或进度条。
class LinkPage extends React.Component {
state = {
builderId: ''
};
componentDidUpdate(prevProps) {
if(this.props.builderId !== prevProps.brokerId) {
this.setState({ builderId: this.props.brokerId });
}
}
render() {
return (
<div className="App">
<h1>{ this.state.builderId ? this.state.builderId : 'Loading' }</h1>
</div>
);
}
}
Or, a simple method would be to not use the lifecycle method at all, Change the following line in render and it should work: 或者,一种简单的方法是根本不使用生命周期方法,在render中更改以下行,它应该可以工作:
<h1>{ this.props.builderId ? this.props.builderId : 'Loading' }</h1>
If you need to use this brokerId for an api call or something, you can use the setState
callback
. 如果您需要将此brokerId用于api调用或其他操作,则可以使用
setState
callback
。 This would go something like this in the componentDidUpdate lifecycle method.
在
componentDidUpdate lifecycle method.
中将执行类似的操作componentDidUpdate lifecycle method.
componentDidUpdate(prevProps) {
if(this.props.builderId !== prevProps.builderId) {
this.setState({ builderId: this.props.builderId }, () => {
//use this.state.brokerIdhere
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.