React native 为什么不应直接更新存储值?
如果我直接更新redux存储值而不是分派操作,会发生什么 下面是一个示例代码:React native 为什么不应直接更新存储值?,react-native,redux,react-redux,React Native,Redux,React Redux,如果我直接更新redux存储值而不是分派操作,会发生什么 下面是一个示例代码: import actions from '../actions' class Example extends Component { static contextTypes = { store: PropTypes.any, } static propTypes = { drawer: PropTypes.object, } compon
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)
状态将更改,但不会将更改通知任何组件
此外,一些优化(如
React.PureComponent
)假设它们可以使用浅层引用相等来检测状态的变化。直接赋值将打破他们的假设。因为如果有其他组件要在uiObjectProp
上重新渲染,则它们不会更改,除非使用dispatch。国家不会真的改变。我想是的,但他们会改变。我不知道我遇到的情况是否特殊。我会更新我的问题。@efkan,有意思。在我的应用程序中,一个嵌套很深的对象是商店的一部分,尝试了同样的方法,但什么也没有发生。根据文档,“改变它内部状态的唯一方法是对它发送一个操作”。我要到处乱拉小提琴!我根据自己的经验改变了这个问题。在我的例子中,this.props.drawer.unread-=1
的代码足以更改抽屉组件值。但是,我的抽屉组件会更改。而且我从不尝试更新更深层的嵌套对象。可能它只适用于第一级对象(如drawer:{unread:3})