【问题标题】:React Redux Toolkit - Can we Dispatch/Call from one reducer's action to another reducer's action to change state variableReact Redux Toolkit - 我们可以从一个 reducer 的动作调度/调用另一个 reducer 的动作来改变状态变量吗
【发布时间】:2022-11-22 03:10:14
【问题描述】:

这里我有两个状态切片,我需要在 slice2 中分派 slice1 的方法。

我如何从 callApiSlice 的额外减速器动作中调用切片 1 的减速器动作

const slice1 = createSlice({
  initialState,
  reducers: {
    login: (state) => {
      state.login = { email: 'email@gmail.com', api_keys: false};
    },
    setApiKey: (state) => {
      state.login.api_keys = true;
    },
  },
}

export const callApi = createAsyncThunk(
  "call-api",
  async (payload, thunkAPI) => {
    try {
      const res = await axios.post( process.env.REACT_APP_API_URL + "/save", payload);
      return res.data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response.data);
    }
  }
);

const callApiSlice = createSlice({
  name: "callApiSlice",
  initialState,
  reducers: {},
  extraReducers: {
    [callApi.fulfilled]: (state, action) => {
      // how to call Slice 1 reducer's action setApiKey to change in login state
    }
  }
});

export default callApiSlice.reducer;

【问题讨论】:

  • 不,reducer 函数是纯的功能,所以应该绝对没有副作用。 setApiKey 需要作为动作发送。这是一个 XY 问题/问题。您在这里真正要解决的用例是什么?你能编辑帖子以包含更完整的minimal reproducible example吗?
  • @DrewReese,谢谢,我更新了问题以使问题更清楚。请告诉我。

标签: javascript reactjs redux react-redux redux-toolkit


【解决方案1】:

您不能直接调用 reducer 函数,但如果我正确理解您的问题,您似乎希望“setApiKey”reducer 函数在发送 callApi.fulfilled 操作时运行。 Redux 状态切片/reducer 函数(即状态减速器树) 在技术上传递了每一个被调度的动作,并且可以响应它们中的任何一个。在 slice1 状态切片中添加一个 reducer case 来处理 callApi.fulfilled 动作。

例子:

const slice1 = createSlice({
  name: "slice1",
  initialState,
  reducers: {
    login: (state) => {
      state.login = { email: 'email@gmail.com', api_keys: false };
    }
    setApiKey: (state) => {
      state.login.api_keys = true;
    }
  },
  extraReducers: {
    [callApi.fulfilled]: (state) => { // <-- respond/react to action
      state.login.api_keys = true;
    },
  },
}
export const callApi = createAsyncThunk(
  "call-api",
  async (payload, thunkAPI) => {
    try {
      const { data } = await axios.post( process.env.REACT_APP_API_URL + "/save", payload);
      return data;
    } catch (error) {
      return thunkAPI.rejectWithValue(error.response.data);
    }
  }
);
const callApiSlice = createSlice({
  name: "callApiSlice",
  initialState,
  extraReducers: {
    [callApi.fulfilled]: (state, action) => {
      ...
    }
  },
});

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 2021-05-05
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2019-10-20
    • 2017-04-02
    • 1970-01-01
    • 2020-12-13
    相关资源
    最近更新 更多