目前我必须重新配置我的商店才能创建选择器。有没有更好的方法来做到这一点。
import { configureStore } from "../configureStore";
const { store } = configureStore();
export const getSession = () => store.getState().session.data || false;
export const getToken = () => store.getState().session.data.token || false;
选择器函数应将存储状态作为参数,而不是捕获存储引用。举个例子:
export const getSession = (state) => state.session.data || false;
export const getToken = (state) => state.session.data.token || false;
// use like:
const session = getSession(store.getState());
请参阅我的帖子惯用的 Redux:使用重新选择选择器进行封装和性能了解更多详细信息。
如果你打算在 React 世界中使用 Redux,那么你一定应该使用
connect
将 redux 存储附加到 React 组件的 props 上 (https://redux.js.org/basics/usage-with-反应)。
这样,每当存储中的值发生变化时,您都会获得提供给组件的更新后的 props,从而使用正确的值重新渲染组件。
这样,您通常就不再需要
store.getState()
。你做类似的事情:
// 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)