如果连接到未更改的商店,则 React componentDidUpdate 方法不会在继承的道具更改时触发 [英] React componentDidUpdate method won't fire on inherited props change if connected to a store that didn't change

查看:19
本文介绍了如果连接到未更改的商店,则 React componentDidUpdate 方法不会在继承的道具更改时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让我的组件知道是否已经加载了某个库.要知道从任何上下文我将它连接到我的商店的库"reducer 到我的组件.我还从调用组件的父级传递了一个配置对象 this.props.dataObject.像这样:

I want my component know if some library is already loaded. To know that from any context i connect it to the "library" reducer of my store to my component. I also pass it a configuration object this.props.dataObject from the parent where the component has been called. Like this:

class GoogleButton extends Component {
    render() {
        if (this.props.libraries.google) {
            return <a id='sharePost' className='google_icon'></a>
        } else {
            return null
        }
    }

    componentDidUpdate() {
        gapi.interactivepost.render('sharePost', this.props.dataObject)
    }
}

function mapStateToProps(state) {
    return { libraries: state.libraries }
}

export default connect(mapStateToProps)(GoogleButton)

处理库状态的reducer是这样的:

The reducer that handles the libraries state is like this:

let newState = {...state}
newState[action.libraryName] = action.state
return newState 

当我更改库状态时 componentDidUpdate 起作用.问题是当我更改父 this.props.dataObject 继承的道具时.在这种情况下,componentDidUpdate 不会触发.如果我从组件中删除 connect 它将按预期工作.我在这里遗漏了什么?

When I change the library state componentDidUpdate works. The problem is when i change the prop inherited by the parent this.props.dataObject. In that case is where componentDidUpdate wont fire. If i remove the connect from the component it works as espected. I'm missing something here?

推荐答案

我解决了.我不是 100% 确定这是准确的,但我会解释.如果我有什么不对的地方,请纠正我.

I solved it. I'm not 100% sure that this is accurate, but I will explain. If im wrong with something, please correct me.

我一直在考虑 Dan 所说的 浅层平等检查他的回答.问题就在那里.我从父对象传递了一个对象,并且该对象的嵌套元素发生了变化.对象保持不变.因此,对于 connect 带来的组件永远不会更新.

I keep thinking about the shallow equality check that Dan said in his answer. The problem was there. I was passing down an object from the parent and the nested elements of that object were the ones that changed. The object remain the same. So with the shallow equality check that connect brings the component will never update.

我的解决方案是在父级使用 Object.assign({}, dataObject) 时传递道具,因此我创建了另一个不同的对象.现在浅层相等检查可以比较它并确定 props 已经改变并且在更新组件之前.

My solution was in the parent use Object.assign({}, dataObject) when I pass down the prop so I make another different object. Now shallow equality check could compare it and determinate that the props have changed and there before update the component.

这篇关于如果连接到未更改的商店,则 React componentDidUpdate 方法不会在继承的道具更改时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆