【问题标题】:Why a store value should not be updated directly?为什么不应该直接更新存储值?
【发布时间】:2017-11-08 07:51:43
【问题描述】:

如果我直接更新 redux 存储值而不是调度操作会发生什么?

这里是一个示例代码:

import actions from '../actions'

class Example extends Component {

    static contextTypes = {
        store: PropTypes.any,
    }

    static propTypes = {
        drawer: PropTypes.object,
    }

    componentDidMount () {
        const { drawer } = this.props 
        const { store } = this.context

        // I can update 'drawer' values directly and "it works" as following
        // drawer.unread -= 1

        // Also I can update 'drawer' values by dispatching an action as following
        drawer.unread -= 1
        this.context.store.dispatch(actions.updateDrawer(drawer))
    }

}


function mapStateToProps(state) {
    return {
        drawer: state.drawer,
    }
}


export default connect(mapStateToProps)(Example)

【问题讨论】:

  • 因为如果您想在uiObjectProp 更改时重新渲染其他组件 - 除非您使用调度,否则它们不会。状态不会真正改变。
  • 我是这么认为的,但他们改变了。我想知道我遇到的情况是不是异常。我会更新我的问题。
  • @efkan ,很有趣。对作为我的应用程序商店的一部分的深层嵌套对象进行了同样的尝试,但没有发生任何事情,并且根据文档“更改其内部状态的唯一方法是对其发送操作”。我会摆弄!
  • 我改变了我所经历的问题。在我的例子中,this.props.drawer.unread -= 1 的代码足以改变 Drawer 组件的值。

标签: react-native redux react-redux


【解决方案1】:

状态会改变,但不会通知任何组件。

此外,一些优化(如React.PureComponent)假设它们可以使用浅引用相等来检测状态的变化。直接赋值会打破他们的假设。

【讨论】:

  • 但是我的抽屉组件发生了变化。此外,我从不尝试更新更深的嵌套对象。也许它只适用于第一级对象(如抽屉:{未读:3})
猜你喜欢
  • 2016-12-13
  • 2014-05-17
  • 1970-01-01
  • 2015-08-21
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
相关资源
最近更新 更多