[英]Extract Redux Store/State as Selector
Currently I'm having to reconfigure my store to create selector. 目前,我必须重新配置商店以创建选择器。 Is there a better way to do this.
有一个更好的方法吗。
import { configureStore } from "../configureStore";
const { store } = configureStore();
export const getSession = () => store.getState().session.data || false;
export const getToken = () => store.getState().session.data.token || false;
Selector functions should take the store state as the argument, not capture the store reference. 选择器函数应将存储状态作为参数,而不是捕获存储引用。 As an example:
举个例子:
export const getSession = (state) => state.session.data || false;
export const getToken = (state) => state.session.data.token || false;
// use like:
const session = getSession(store.getState());
See my post Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance for more details. 有关更多详细信息,请参阅我的文章惯用法Redux:使用重新选择选择器进行封装和性能 。
If you are going to use Redux in React world, then you should definitely attach the redux store to the props of a React component by using connect
( https://redux.js.org/basics/usage-with-react ). 如果您打算在React世界中使用Redux,那么您绝对应该通过使用
connect
( https://redux.js.org/basics/usage-with-react )将redux存储附加到React组件的props上。
That way, whenever the values in the store changes, you get updated props provided to your component, re-rendering the component with the correct values. 这样,只要存储中的值发生更改,您就会获得提供给组件的更新道具,并用正确的值重新渲染组件。
With that, you generally don't ever need store.getState()
. 这样,您通常就不需要
store.getState()
。 You do something like: 您可以执行以下操作:
// selectors.js
const getSession = state => state.session.data || false
// component.js
const MyComponent = ({ session }) => <div>{session}</div>
const mapStateToProps = state => ({
session: getSession(state),
})
export default connect(mapStateToProps)(MyComponent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.