【问题标题】:How does this extraReducers processing work?这个 extraReducers 处理是如何工作的?
【发布时间】:2021-07-04 09:22:46
【问题描述】:

我有多个 thunk 操作,我想以不同的方式处理它们的完成状态。我有一个extraReducers 的切片,如下所示:

extraReducers: {
  // Add reducers for additional action types here, and handle loading state as needed
  [getRoot.fulfilled]: (state, action) => {
    state.data = action.payload;
    console.log('getRoot');
  },
  [getChildren.fulfilled]: (state, action) => {
    var parent = findParent(state.data, action.parentId);
    parent.items.push(action.payload.children);
    console.log('getChildren');
  }
}

然后像这样 thunk 操作:

export const getRoot = createAsyncThunk('data/nodes/getRoot', async () => {
    console.log('getRoot invoked');
    const response = await axios.get('http://localhost:5000/api/nodes/root');
    const data = await response.data;
    return data;
});

export const getChildren = createAsyncThunk('data/nodes/getRoot', async params => {
    console.log('getChildren invoked');
    const response = await axios.get('http://localhost:5000/api/nodes/' + params.id + '/children');
    const data = await response.data;
    return data;
});

我现在遇到的问题是,当我调用getRoot 操作时,getChildren.fulfilled 被处理,我不明白为什么。

这是我的控制台输出:

getRoot invoked
getChildren completed

【问题讨论】:

    标签: reactjs redux redux-thunk redux-toolkit


    【解决方案1】:

    这是因为您创建了两个不同的异步 thunk具有相同的操作类型字符串前缀'data/nodes/getRoot'

    从那里,您将有效地创建两个不同的对象键,它们是相同的字符串:

    extraReducers: {
      'data/nodes/getRoot/fulfilled': (state, action) => {
        state.data = action.payload;
        console.log('getRoot');
      },
      'data/nodes/getRoot/fulfilled': (state, action) => {
        var parent = findParent(state.data, action.parentId);
        parent.items.push(action.payload.children);
        console.log('getChildren');
      }
    }
    

    当你在 JS 的一个对象中定义了两次相同的键时,第二个定义会覆盖第一个。

    解决方法是给每个 thunk 一个唯一的操作类型字符串前缀。

    【讨论】:

      猜你喜欢
      • 2021-06-18
      • 2022-12-11
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多