为什么商店价值不应该直接更新?

时间:2017-11-08 07:51:44

标签: react-native redux react-redux

如果直接更新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)

1 个答案:

答案 0 :(得分:0)

状态将发生变化,但不会通知任何组件变更。

此外,一些优化(如React.PureComponent)假设他们可以使用浅参考相等性来检测状态的变化。直接分配将打破他们的假设。