【问题标题】:redux-toolkit extraReducers not being invokedredux-toolkit extraReducers 未被调用
【发布时间】:2020-10-17 07:00:56
【问题描述】:

我正在尝试 createAsyncThunk,但无法触发 extraReducers。这是我现在拥有的:

export const getAllAgents = createAsyncThunk(
  "getAllAgents",
  async (token: string) => {
    let headers = new Headers();
    headers.append("Authorization", `Bearer ${token}`);
    headers.append("Content-Type", "application/json");
    const response = await fetch(`${API.endpoint}/data/agent`, {
      method: "get",
      headers,
      redirect: "follow",
    });
    const data = await response.json();
    console.log("Response in thunk: ", { data });
    return data;
  }
);

export const agentSlice = createSlice({
  name: "agentSlice",
  initialState,
  reducers: {},
  extraReducers:
    //builder call back required for typesafety
    //https://redux-toolkit.js.org/usage/usage-with-typescript#type-safety-with-extrareducers
    (builder) => {
      console.log(createNewAgent.fulfilled);
      builder.addCase(createNewAgent.fulfilled, (state, action) => {
        console.log("fulfilled action", { action });
      });
      console.log(getAllAgents.fulfilled);
      builder.addCase(getAllAgents.fulfilled, (state, action) => {
        state.agents = action.payload.agents;
      });
    },
});

我还看到在开发工具中调用了已完成的操作:

有什么问题?

【问题讨论】:

  • 愚蠢的问题:你把agentSlice.reducer插入configureStore了吗?
  • 是的!原来是这样!
  • 我犯了类似的错误,想知道为什么它不起作用。

标签: reactjs typescript redux redux-toolkit


【解决方案1】:

我遇到了同样的问题。我的错误是我在 extraReducers 之外添加了减速器。

这是错误的:

const authSlice = createSlice({
  name: 'auth',
  initialState,
  extraReducers: {
    [login.fulfilled]: (state, action) => {},
   },
   [signUp.fulfilled]: state => {}
}

【讨论】:

  • 我的接近这个,只是我不小心在减速器之后添加了一个额外的花括号,所以我的额外减速器实际上在我的减速器中,哈哈
猜你喜欢
  • 2023-01-19
  • 2021-09-11
  • 2021-12-10
  • 1970-01-01
  • 2020-06-11
  • 2021-03-14
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
相关资源
最近更新 更多