gpt4 book ai didi

javascript - ReactJs - 从 reducer 返回相同状态时不会触发 componentWillReceiveProps

转载 作者:行者123 更新时间:2023-11-30 15:22:37 25 4
gpt4 key购买 nike

我在我的应用中使用了 React 和 React-redux。在提交表单数据时,我在 redux 操作中调用 API 并将其分派(dispatch)给 reducer。 reducer 返回“{ ...state, message : action.message }” 当我的组件连接到商店时,它又调用 componentWillReceiveProps 生命周期方法。目前一切正常。

当用户第二次填写表单并提交时,重复相同的操作。但是现在 componentWillReceiveProps 函数没有被触发。这背后的原因是 reducer 返回类似于先前状态数据的相同状态“{ ...state, message : action.message }”。如果我在 reducer 中添加一个带有随机数的新对象,如下所示,一切正常。

{ ...state, message : action.message, random : Math.random() }

我知道 componentWillReceiveProps 是在 store 改变的时候触发的。但是如何在提交表单时第二次触发componentWillReceiveProps方法呢?

这是我的 componentWillReceiveProps 方法,我在其中向用户显示成功消息。

componentWillReceiveProps = props => {
if( typeof props.message !== "undefined" && props.message !== "" ){
//Show a success message notification bar
this.state._notificationSystem.addNotification({
title : 'Success message',
message: 'Form has been successfully submitted',
level: 'success',
position : 'br',
autoDismiss : 10
});
}
}

最佳答案

react-redux 让你强制重新渲染包装组件,即使它的 props 没有改变。为此,您必须将 { pure: false } 选项作为 connect 函数的第四个参数传递。

可以找到快速示例here .

但是在你的情况下它看起来像一个反模式。首先,它会在所有状态变化时更新,即使那些状态与表单提交无关。其次,我会说这种逻辑(即“让我们在成功时显示通知”)应该存在于执行事务的 Action 中,而不是组件中。

关于javascript - ReactJs - 从 reducer 返回相同状态时不会触发 componentWillReceiveProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469902/

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