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

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

问题描述

我希望我的组件知道是否已加载某个库。要知道从任何上下文我将它连接到我的商店的库减少器到我的组件。
我还从已调用组件的父项传递配置对象 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.

我一直在想浅层平等检查。问题出在那里。
我从父对象传递一个对象,该对象的嵌套元素是那些已更改的对象。对象保持不变。因此,使用浅等式检查连接使组件永远不会更新。

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)中所以我做了另一个不同的对象。现在,浅层等式检查可以比较它并确定道具已经更改,并在更新组件之前进行更改。

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方法将不会触发继承的props更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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