[英]react-native : state not updated inside the componentWillReciveProps
我正在尋找很多方法來解決這個問題,但是沒有人可以使用, 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>
);
}
}
如果我做console.log(nextProps.data+"=this id")
它可以將我想要更新的id返回到this.state.ids
。 但是在渲染中的<Text>{this.state.ids}</Text>
中仍顯示this.state.ids
('ger')的默認值,這意味着this.state.ids
在componentWillReceiveProps
未更新。
在我看來,這是一種反模式。 為什么不將nextProps.data作為ID直接注入到Detail組件中? 然后,您可以像這樣直接輸出id:
<Text>{this.props.ids}</Text>
通常,您還應該得到一條警告,即在“ componentWillReceiveProps”中調用setState將無效。 如果您確實想更新狀態,則可以執行“ this.state.ids = nextProps.data”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.