簡體   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