简体   繁体   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

Here I have two state slices and I need to dispatch a method of slice1 within slice2.这里我有两个 state 切片,我需要在 slice2 中调度 slice1 的方法。

How can I call a reducer's action of slice 1 from extra reducer's action of callApiSlice我如何从 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;

You can't directly invoke reducer functions, but if I'm correctly understanding your question it seems you want "setApiKey" reducer function to run upon dispatch of the callApi.fulfilled action.您不能直接调用 reducer 函数,但如果我正确理解您的问题,您似乎希望“setApiKey”reducer function 在调度callApi.fulfilled操作时运行。 Redux state slices/reducer functions ( ie the state reducer tree ) are technically passed every action that is dispatched, and can respond to any of them. Redux state 切片/reducer 函数(即 state reducer 树)在技术上传递了每个调度的动作,并且可以响应它们中的任何一个。 Add a reducer case in the slice1 state slice to handle the callApi.fulfilled action.slice1 state 切片中添加一个 reducer case 来处理callApi.fulfilled动作。

Example:例子:

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