问题描述
我一直在学习 Redux,但我不清楚的部分是,我如何在使用 react state 与 redux store 之间做出决定,然后再调度 action.从我目前的阅读来看,我似乎可以使用 React 状态代替 Redux 存储,并且仍然可以完成工作.我理解使用 Redux 存储和只有 1 个容器组件而其余部分作为无状态组件的关注点分离,但我如何确定何时使用 React 状态与 redux 存储对我来说不是很清楚.有人可以帮忙吗?
I've been learning Redux and a part I'm unclear of is, how do I make a determination between using react state vs redux store and then dispatching actions. from my reading so far it looks like I could use React state in place of Redux store and still get things done. I understand the separation of concerns with using Redux store and just having 1 container component and the rest of it as stateless component but how do I make the determination of when to use React state Vs redux store is not very clear to me. Can someone please help?
谢谢!
推荐答案
如果状态不需要与其他组件共享,或者组件卸载时不需要保持状态,那么你可以只需将其置于组件状态即可.
If the state doesn't need to be shared with other components, or the state doesn't need to be keep when the component is unmounted, then you can just put it in the component's state.
你可以认为Redux store是前端的数据库,如果你有从API中获取的产品数据之类的东西,那么Redux store就是正确的地方;如果您有一个下拉组件,它需要一个 isOpen
属性,那么该下拉组件的父级可以将 dropdownIsOpen
作为组件状态.
You can think that the Redux store is the database of front-end, if you have something like product data fetched from an API, then the Redux store is the right place; if you have a dropdown component, which takes a isOpen
prop, then the parent of that dropdown can just keep dropdownIsOpen
as a component state.
欲了解更多信息,这里是 Dan 的回答:https://github.com/reactjs/redux/issues/1287
For more information, here is the answer from Dan: https://github.com/reactjs/redux/issues/1287
你也说
只有 1 个容器组件,其余为无状态组件
这是不正确的.您可以有多个容器组件.一个容器组件还可以包含另一个容器组件.
This is incorrect. You can have several container components. A container component can also contain another container component.
这篇关于我什么时候选择 React state 和 Redux Store的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!