gpt4 book ai didi

javascript - react native : state not updated inside the componentWillReciveProps

转载 作者:行者123 更新时间:2023-12-03 03:24:33 25 4
gpt4 key购买 nike

我一直在寻找很多方法来解决这个问题,但没有一个有效,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 中更新。

最佳答案

setState() 并不总是立即更新组件。

您可以在 here 上找到您需要的一切.

实际上,正如 React 文档所说,“React 在安装过程中不会使用初始 props 调用 componentWillReceiveProps。它仅在某些组件的 props 可能更新时调用此方法。调用 this.setState 通常不会触发 componentWillReceiveProps。”

您可以找到更多here .

关于javascript - react native : state not updated inside the componentWillReciveProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com