Redux 工具包访问组件外部的存储值
Redux tookit access store values outside of component
如何在 React 组件之外访问 redux-toolkit store
变量?在 React 组件中,我可以使用
访问它
import { useSelector } from 'react-redux';
const isAuthenticated: boolean = useSelector(
(state: RootState) => state.user.isAuthenticated,
);
因为 useSelector 不允许在 React 之外访问。或者我应该在 React Component 中调度时传递变量?我需要在 createAsyncThunk
API 调用
中访问变量
createAsyncThunk 将传入一个 thunkApi
对象作为有效负载创建者回调的第二个参数,您可以在该对象上调用 getState
方法。
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (someArg, thunkApi) => {
const state = thunkApi.getState()
// whatever logic you need.
const response = await userAPI.fetchById(someArg)
return response.data
}
)
如何在 React 组件之外访问 redux-toolkit store
变量?在 React 组件中,我可以使用
import { useSelector } from 'react-redux';
const isAuthenticated: boolean = useSelector(
(state: RootState) => state.user.isAuthenticated,
);
因为 useSelector 不允许在 React 之外访问。或者我应该在 React Component 中调度时传递变量?我需要在 createAsyncThunk
API 调用
createAsyncThunk 将传入一个 thunkApi
对象作为有效负载创建者回调的第二个参数,您可以在该对象上调用 getState
方法。
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (someArg, thunkApi) => {
const state = thunkApi.getState()
// whatever logic you need.
const response = await userAPI.fetchById(someArg)
return response.data
}
)