【问题标题】:React-Redux: State Changes Don't Call mapStateToPropsReact-Redux:状态更改不要调用 mapStateToProps
【发布时间】:2019-11-10 17:45:28
【问题描述】:

我正在尝试让 redux 在我的应用程序中运行,但在将状态更改传递给连接的组件时遇到了问题。 mapStateToProps 函数仅在初始化时被调用,并且不再被调用。

我已经阅读了Troubleshooting 页面以及论坛和 github 问题上的无数帖子。我已经 100% 确保我没有变异状态。我已经应用了中间件,它比较了一个动作被调度之前和之后的状态,以帮助验证至少有一个新的引用。

这是确保调度操作创建新存储引用的基本中间件

//Store Maker code to apply middleware
const logger = (store) => (next) => (action) => {

    var old_state = store.getState()

    var result = next(action)

    var new_state = store.getState()

    console.log("ENSURE FALSE", new_state === old_state)

    return result
}

export default () => {
    return applyMiddleware(logger)(createStore)(reducers)
}

这是我创建商店并将其提供给子组件的位置的快照

//Parent Component code
const store = StoreMaker()

const unsubscribe = store.subscribe(() => {
    console.log("State Changed", store.getState())
})

...

class Plugin extends React.Component{

    ...

    render(){
        return (
            <Provider store={store}>
                <ChildComponent {...this.props} />
            </Provider>
        )
    }
}

这是我在尝试使其工作时正在使用的最基本且毫无意义的减速器

//Reducer code
export default (state={}, action) => {
    if(action.type === "init"){
        return {
            ...state,
            test: 1
        }
    }
    else{
        return {
            ...state,
            test: 2
        }
    }
}

最后,这是子组件

//Child Component code
class ChildComponent extends React.Component{
    constructor(props){
        super(props)
    }

    ...

    render(){
        return (
            this.props.test
        )
    }
}

const mapStateToProps = (state) => {
    console.log("Mapping state to props")
    return state
}

export default connect(mapStateToProps)(ChildComponent)

据我了解,react-redux 中的 connect 函数订阅 store 并在通过 mapStateToProps 发生更改时更新连接组件的 props。但是,当我的商店发生状态更改时,mapStateToProps 不会被调用,并且连接组件的 props 不会更改。但是我在父组件中手动编码只是为了记录状态的订阅确实触发了,这让我对为什么没有调用 mapStateToProps 感到困惑。

我无法弄清楚出了什么问题,而且我正在镜像几乎相同的工作示例。如果我能得到一些帮助,那就太好了。

即使只是关于如何进行调试的想法也将不胜感激。我正在尝试使用 Chrome 开发工具在订阅状态更改并调用 mapStateToProps 的 react-redux 代码中设置断点,但我无法理解源代码中发生了什么。我正在尝试查明我的代码无法将状态更改传达给我连接的组件的位置。

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    我想知道是否是 JavaScript 原语有问题的更改检测(这意味着它可能是 JavaScript 限制,而不是 React/Redux 限制)。你可以修改你的例子,而不是你的state 是一个数字原语,它是一个以该数字原语作为属性的 JavaScript 对象吗?例如:

    将状态从 state = 0 更改为 state = { value: 0 }

    如果解决了问题,请告诉我。

    【讨论】:

    • 我已经编辑了我的回复以反映您的要求(我相信),但不幸的是 mapStateToProps 仍未被调用
    【解决方案2】:

    如果有人想知道,上面的代码确实有效。

    我正在尝试使用 react@16.8.6redux@4.0.1react-redux@6.0.0

    在不更改任何代码的情况下,我的问题实际上是通过切换到react@16.5.2 解决的(保持redux@4.0.1react-redux@6.0.0)。

    不知道为什么这会修复它,但确实如此。写这个以防其他人有类似的问题。

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 2021-01-12
      • 2021-07-27
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2021-01-27
      相关资源
      最近更新 更多