gpt4 book ai didi

reactjs - setState 未在 componentWillReceiveProps 内部更新

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

我觉得我正在以正确的方式调用 setState,但我想确保我没有在错误的地方进行调用。看看是否有人能发现错误。在控制台日志中,状态保持以前的值,而不是新的清除值。这是我的代码:

componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.state.value && typeof nextProps.value !== 'undefined'){
let changeVal = nextProps.value;
let changeDisplay = nextProps.value;
if(this.props.entryType === 'date') changeVal = Moment(nextProps.displayValue).format(this.props.format).toString();
if(this.props.entryType === 'currency'||this.props.entryType === 'number'){
if(isNaN(parseFloat(changeVal))){
changeVal = 0;
changeDisplay = 0;
}
}
if(this.props.entryType === 'drop' || this.props.entryType === 'boolean'){
if(this.props.options) {
this.props.options.map(x => {
if (x.value == changeVal || x.sortOrder == changeVal){
changeDisplay = x.label;
changeVal = x.value;
}
})
}
}
this.setState({value: changeVal, displayValue: changeDisplay, selectValue:{value:changeVal, label:changeDisplay}}, ()=>{
console.log("current displayValue",this.state, nextProps, this.props)
});
}
}

很明显我在 setState 之后调用了控制台,但是值没有更新。

编辑:感谢您的回复。我将尝试分解 Prop 更新状态方法。我创建了一个拖放系统,可以将项目拖入和拖出组。效果很好,但它在该层次结构中有一个 Container > Tree > Item > QueryValue 组件。这里的问题在于 Container 需要知道整个树,以便能够构建它,但是对内容的编辑发生在 QueryValue 中。所以我有一个方法可以通过链,它允许我通知 Container 任何更改。但我可能需要将 Container 数据与 QueryValue 数据分离。

最佳答案

您的代码非常复杂,所以我建议尝试重构它。

但无论如何,我建议使用“componentDidUpdate”

  • 因为“componentWillReceiveProps”已被弃用并且会导致副作用和复杂的状态流,这有利于代码中的错误

React 文档(对于“componentDidUpdate”):

https://reactjs.org/docs/react-component.html#componentdidupdate


React 文档(针对“UNSAFE_componentWillReceiveProps”):

https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops


Note: 

Using this lifecycle method often leads to bugs and inconsistencies, and for that reason it is going to be deprecated in the future.

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

For other use cases, follow the recommendations in this blog post about derived state.

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

If you used componentWillReceiveProps to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

In very rare cases, you might want to use the getDerivedStateFromProps lifecycle as a last resort.

关于reactjs - setState 未在 componentWillReceiveProps 内部更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51634046/

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