0

通常、サンクでは、他のアクションを呼び出すことになります。

const startRecipe = {type: "startRecipe"}

const reducer = (state, action) => {
  if (action.type === "startRecipe") { 
    state.mode = AppMode.CookRecipe
  }
}

const getRecipeFromUrl = () => async dispatch => {
  const res = await Parser.getRecipeFromUrl(url)
  dispatch(startRecipe)
}

redux ツールキットでは、これcreateAsyncThunkはそれほど簡単ではありません。実際、次の結果のアクションから状態を変更できますextraReducers

export const getRecipeFromUrl = createAsyncThunk('getRecipeFromUrl',
  async (url: string): Promise<RecipeJSON> => await Parser.getRecipeFromUrl(url)
)

const appStateSlice = createSlice({
  name: 'app',
  initialState: initialAppState,
  reducers: {},
  extraReducers: ({ addCase }) => {
    addCase(getRecipeFromUrl.fulfilled, (state) => {
      state.mode = AppMode.CookRecipe
    })
  }
})

しかし、レシピを開始する非同期の方法も必要です。これには、スライスにレデューサーが必要です。

  reducers: {
    startRecipe(state): state.mode = AppState.CookRecipe
  },

同じコードを 2 つの場所に記述することを避けるために、サンク ハンドラーから単純なレデューサー関数を呼び出せるようにしたいと考えています。startRecipe(state)ケースから簡単に and startRecipe(アヒルのエクスポート用に分解されていたので、正しい関数を参照していたと確信しています)を試しましextraReducersたが、うまくいきません。

_startRecipe私の現在の解決策は、スライスの外側で定義し、両方の場合でその関数を参照することです

  reducers: { startRecipe: _startRecipe },
  extraReducers: builder => {
    builder.addCase(getRecipeFromUrl.fulfilled, _startRecipe)
  }

slice.reducersでシンプルなアクションを定義し、サンク ハンドラから参照できる「より良い」方法はありますextraReducersか?

4

2 に答える 2