哪些数据需要存在redux的store中,怎么权衡

哪些数据需要存在redux的store中,哪些数据单独写在组件state中

怎么权衡?

还是说所有状态都写在store?

阅读 7k
5 个回答

把组件需要共享的状态放到 store 里即可, 组件自己维护内部状态.

作者原话:

Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft.

Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local).

The rule of thumb is: do whatever is less awkward.

临时数据,可以放state
需要共享的,放store,比如A组件的操作会导致B组件数据改变的,举个例子,header里面有搜索条,搜索内容会导致当前页面的列表发生改变,这时候就可以把数据放store,在header里dispatch一个action,改变对应的state数据,这样,通过connect把mapStateToProps绑定到列表组件内,就可以实时渲染列表

组件自己需要临时使用的状态放在state,其它的放在Store,但也没法完全权衡利弊

把组件间需要共享的数据保存在store中,方便组件间通信。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题