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

标签 javascript reactjs react-native react-redux

我在我的应用中使用了 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/

相关文章:

javascript - 组件不在 .map forEach 中呈现

javascript - 如何在React Native中解析html

ios - 我想要创建 native 模块还是 native UI 组件?

JavaScript RegExp 排除特定文件扩展名和index.js

javascript - 如何在单击父 div 时切换无序列表中元素上的类?

javascript - 如何使用帖子:title in url instead of :id in React. js

javascript - 在 ReactJs 中渲染对象数组

javascript - 从 firebase 函数返回

javascript - 使用 javascript 连接到现有的 sqlite 数据库

javascript - 将变量传递给 JavaScript