Reactjs 触发CreateSynchThunk以从CreateSicle中发布附加数据?可能的

Reactjs 触发CreateSynchThunk以从CreateSicle中发布附加数据?可能的,reactjs,typescript,redux-toolkit,Reactjs,Typescript,Redux Toolkit,我有两个api,一个是向fighters表添加MMA fighter,另一个是获取所有权重类的api,以填充我的一个菜单。如果我添加的是权重类当前不在weightclass表中的fighter,我需要通过我的weightclass api端点添加新的weightclass记录 因此,这是我第一次呼吁添加一个新的战斗机: export const addFighter = createAsyncThunk( 'fighters/addFighter', async (fighter: fi

我有两个api,一个是向fighters表添加MMA fighter,另一个是获取所有权重类的api,以填充我的一个菜单。如果我添加的是权重类当前不在weightclass表中的fighter,我需要通过我的weightclass api端点添加新的weightclass记录

因此,这是我第一次呼吁添加一个新的战斗机:

export const addFighter = createAsyncThunk(
  'fighters/addFighter',
  async (fighter: fighterInterface, { dispatch }) => {
    return fetch('fightersAPIEndpoint/fighters', {
      method: 'POST',
      body: JSON.stringify(fighter),
      headers: { 'Content-Type': 'application/json' },
    }).then((res) => res.json())
       .then(() => {
         dispatch(checkWeightClass(fighter.weightclass))
       })
  }
)
checkWeightClass减速机在我的CreateSicle中,我需要在添加它之前检查这个新战斗机的weightclass当前是否存在,因此我在checkWeightClass中有逻辑来检查:

checkWeightClass: (state, { payload }) => {
      let findWeightClass = state.weightclasses.find((w) => {
        if (w.name === payload) {
          return true
        }
      })

      if (findWeightClass) {
      } else {      
        // if the weightclass doesn't exist, I will want to call this other createAsyncThunk
        dispatch(addWeightClass(payload))
      }
}

但它不让我,我如何才能做到这一点?我不能马上调用addWeightClass API,因为我需要先检查它是否存在,谢谢

在减速机内分派操作是一个复杂的过程。减速器应该只处理状态的变化而没有副作用

另一种方法是在
addFighter
内部调度
addWeightClass
操作,并在api回调内部执行检查:

async(fighterInterface,{dispatch,getState})=>{
const{weightclasses}=getState().fighters;//从redux状态开始的绝对路径
返回获取('FightersPaiendPoint/fighters'{
方法:“POST”,
正文:JSON.stringify(fighter),
标题:{'Content-Type':'application/json'},
})
.然后((res)=>res.json())
.然后(()=>{
const findWeightClass=weightclass.find((w)=>w.name=fighter.weightclass);
如果(!findWeightClass){
签派(addWeightClass(战斗机重量级));
}
})
}

请注意,
getState
检索整个状态,而不仅仅是像reducer那样的相对路径。

谢谢,我们将尝试一下!我想出了一个解决办法,在我的状态下创建更多属性来跟踪我是否应该调用addWeightClass CreateAynchThunk函数,但是你的解决方案要优雅得多,如果它能工作,我会报告回来!