【发布时间】:2020-07-17 15:51:51
【问题描述】:
我试图在页面加载时在 useEffect 中启动调度操作,以检索 JSON 并填充对象。
dispatch 函数,如果它是通过另一个调用单独调用就可以正常工作,并且 useEffect 还处理其他逻辑,但是当这两者结合时,dispatch action 不会从内部触发。我还编写了一个回调函数,并尝试从 useEffect 中调用它,但没有任何运气。任何反馈将不胜感激。
const dispatch = useDispatch();
useEffect(() => {
dispatch(actions.loadCountries);
}, [dispatch]);
---------------------------
Using redux toolkit and create slice
export const initialState: ContainerState = {
countriesLoading: false,
countriesError: null,
countries: [],
};
const initiateSlice = createSlice({
name: 'home',
initialState,
reducers: {
loadCountries(state) {
state.countriesLoading = true;
state.countriesError = null;
state.countries = [];
},
countriesLoaded(state, action: PayloadAction<ICountry[]>) {
state.countries = action.payload;
state.countriesLoading = false;
},
countriesError(state, action: PayloadAction<ErrorType>) {
state.countriesError = action.payload;
state.countriesLoading = false;
},
},
});
export const { actions, reducer, name: sliceKey } = initiateSlice;
--------------
Selector
const selectDomain = (state: RootState) => state.initiate || initialState;
export const selectCountriesLoading = createSelector(
[selectDomain],
initiateState => initiateState.countriesLoading,
);
export const selectCountriesError = createSelector(
[selectDomain],
initiateState => initiateState.countriesError,
);
export const selectCountries = createSelector(
[selectDomain],
initiateState => initiateState.countries,
);
【问题讨论】:
-
显示您的问题的最小表示,
actions.loadCountries看起来如何?它是一个函数吗? How to create a Minimal, Reproducible Example -
展示你的减速器和动作也会很有帮助。特别是如果其中一些工作正常,而您只是对此特定操作有疑问。
-
我已经更新了原始帖子的代码。如果 Dispach 在附加到另一个事件(如 onChange 或 onClick)的函数上调用,则 Dispach 使用 saga 工作并提供正确的 JSON。我正在使用带有打字稿的github.com/react-boilerplate/react-boilerplate-cra-template starter。
标签: reactjs redux react-hooks