【问题标题】:Dispatch is not firing inside useEffect on you page load页面加载时,调度未在 useEffect 内触发
【发布时间】: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


【解决方案1】:

嗯...尝试在动作名称的末尾添加()

调度(actions.loadCountries**()**)

【讨论】:

  • 太棒了。这成功了 Vitalik!谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2017-07-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多