gpt4 book ai didi

javascript - 无法检测到 ComponentDidUpdate 中连接到 Redux Store 的 Prop 的变化

转载 作者:行者123 更新时间:2023-11-30 14:11:06 24 4
gpt4 key购买 nike

出于某种原因,我无法检测到 ComponentDidUpdate() 中 props 的变化。

父组件:

class Parent extends Component{

componentDidUpdate(prevProps,prevState){
// here, prevProps is the same as this.props even though the
// consultations object is changed by the date component
}

render(){
return(
<p>{this.props.consultation.date}</p> /* Changes when date
component changes the date. This works! */
<DateComponent />
);
}
}
function mapStateToProps({consultation}){
return {consultation}
}

export default connect(mapStateToProps, null)(Parent)

日期组件用于更改咨询日期。我确保我不会改变 reducer 中的状态并使用 Object.assign() 返回一个新对象。

当 DateComponent 更改咨询日期时,“p 标签”中的日期会完美更改

在ComponentDidUpdate中,prevProps.consultation.date & this.props.consultation.date是相等的。

两者都有新的日期值!我以为 prevProps.consultation.date 会给我更早的日期!

我被卡住了,因为我无法检测到日期的变化并在 ComponentDidUpdate() 中执行必要的操作。

如果有人能指出我可能出错的地方,我将不胜感激。

谢谢大家

编辑:****Reducer代码按要求****

case DATE_CHANGE_SUCCESS:
var consultation = {...state}
consultation.date = action.data.date;
return Object.assign({},state,{consultation});

最佳答案

该问题与对象的深度复制有关。

我的咨询对象有这种结构:

consultations = {
3322345: {id:123,date:10/10/2018},
1234567: {id:456,date:10/10/2018}
}

我的错误是在 reducer 中,我会首先像这样复制当前状态:

var consultations_copy = {...state.consultations}

这是一个大错误!因为这不会对对象进行深拷贝,并且仍然引用原始对象。

所以当我进行像 consultations[1234567].date = "12/12/2018"这样的更改时,我实际上是在更改原始对象!

进行深拷贝的最佳方式是:

var consultations_copy = JSON.parse(JSON.stringify(state.consultations));

关于javascript - 无法检测到 ComponentDidUpdate 中连接到 Redux Store 的 Prop 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441048/

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