繁体   English   中英

React Redux 工具包 - 我们可以从一个 reducer 的操作调度/调用另一个 reducer 的操作来更改 state 变量

[英]React Redux Toolkit - Can we Dispatch/Call from one reducer's action to another reducer's action to change state variable

这里我有两个 state 切片,我需要在 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”reducer function 在调度callApi.fulfilled操作时运行。 Redux state 切片/reducer 函数(即 state reducer 树)在技术上传递了每个调度的动作,并且可以响应它们中的任何一个。 slice1 state 切片中添加一个 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) => {
      ...
    }
  },
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM