[英]react-native : state not updated inside the componentWillReciveProps
i was searching so many ways to solve this, but no one works, setState
still not working inside the componentWillReciveProps
method here is my code : 我正在寻找很多方法来解决这个问题,但是没有人可以使用,
setState
仍然无法在componentWillReciveProps
方法内部工作,这是我的代码:
export class Detail extends React.Component
{
constructor(props)
{
super(props);
this.state = {
ids: 'ger'
}
}
componentWillReceiveProps(nextProps) {
this.setState({ ids: nextProps.data }, () => {
console.log(nextProps.data+"=this id")
});
}
render()
{
return (
<View>
<Text>{this.state.ids}</Text>
</View>
);
}
}
if i do console.log(nextProps.data+"=this id")
it can return the id that i want to update to this.state.ids
. 如果我做
console.log(nextProps.data+"=this id")
它可以将我想要更新的id返回到this.state.ids
。 But in the <Text>{this.state.ids}</Text>
in the render still shows the default value of this.state.ids
('ger') , means that this.state.ids
did not updated in the componentWillReceiveProps
. 但是在渲染中的
<Text>{this.state.ids}</Text>
中仍显示this.state.ids
('ger')的默认值,这意味着this.state.ids
在componentWillReceiveProps
未更新。
setState() does not always immediately update the component. setState()并不总是立即更新组件。
you could find all you need on here . 您可以在这里找到所需的一切。
actually as react document saya "React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update. Calling this.setState generally doesn't trigger componentWillReceiveProps." 实际上作为反应文档说:“在安装过程中,React不会使用初始道具来调用componentWillReceiveProps。它仅在组件的某些道具可能更新时才调用此方法。调用this.setState通常不会触发componentWillReceiveProps。”
This looks like an antipattern to me. 在我看来,这是一种反模式。 Why are you not injecting nextProps.data directly as ids into the Detail component?
为什么不将nextProps.data作为ID直接注入到Detail组件中? Then you can output the ids directly like this:
然后,您可以像这样直接输出id:
<Text>{this.props.ids}</Text>
Usually you should also get a warning that calling setState in "componentWillReceiveProps" will have no effect. 通常,您还应该得到一条警告,即在“ componentWillReceiveProps”中调用setState将无效。 If you really wanted to update your state instead you can do "this.state.ids = nextProps.data" I think.
如果您确实想更新状态,则可以执行“ this.state.ids = nextProps.data”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.