【发布时间】:2017-09-24 12:56:06
【问题描述】:
我正在寻找很多方法来解决这个问题,但没有一个有效,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 中没有更新。
【问题讨论】:
-
我认为这与您的previous question 有关,可能是由于您的
ListView上的渲染项目上没有key属性。请看this answer -
我试过了,还是会出现这个问题,奇怪的是
nextProps.data在我做console.log(nextProps.data+"=this id")的时候成功获取了id(比如输出是“4=this id”)但是ids状态仍然没有更新,即使我已经在componentWillReceiveProps里面做了this.setState({ ids: nextProps.data }):'(