[英]How to access my redux state outside of the functional component or class component?
I have created a reducer called auth and persisted in this reducer.我创建了一个名为 auth 的减速器并坚持使用这个减速器。
I want to get auth value outside of the functional component or class component, for example in the utils.我想在功能组件或 class 组件之外获取 auth 值,例如在 utils.xml 中。 How can I do that?
我怎样才能做到这一点?
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LoginSuccess = (payload) => {
return {
type: LOGIN_SUCCESS,
payload
};
};
import { LOGIN_SUCCESS } from './authAction';
// INITIAL TIMER STATE
const initialState = {
user: {}
};
// Auth REDUCER
export const authReducer = (state = initialState, { type, payload }) => {
switch (type) {
case LOGIN_SUCCESS:
return { ...state, user: payload };
default:
return state;
}
};
const reducers = {
auth: authReducer
};
const persistConfig = {
key: 'primary',
storage,
whitelist: ['auth'] // place to select which state you want to persist
};
This is not really "react-redux" way.这不是真正的“react-redux”方式。 Your store is a part of react application that is just big react component.
您的商店是反应应用程序的一部分,它只是一个大型反应组件。 However, you can create your store in separate module outside of your application and use it where you want importing instance of your store.
但是,您可以在应用程序之外的单独模块中创建您的商店,并在您想要导入商店实例的地方使用它。
For example, you are creating your store in store.js
:例如,您在
store.js
中创建商店:
// store.js
export default createStore(reducer, preloadedState, enhancers);
Then, you can import it inside your react application然后,您可以将其导入到您的反应应用程序中
// app.jsx
import store from '/path/to/store';
import { Provider } from 'react-redux';
function App () {
<Provider store={store}>{everything else}</Provider>
}
and inside your utils在你的工具里面
// my-util.js
import store from '/path/to/store';
function util() {
// do whatever you want with same instance of store
// for example, return current state
return store.getState()
}
You can subscribe to store, if you need or just get current state.您可以订阅商店,如果您需要或只是获取当前的 state。 Or you can do complex stuff with replacing reducers for seamless client side updates.
或者,您可以通过替换减速器来完成复杂的工作,以实现无缝的客户端更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.