这个 extraReducers 处理是如何工作的?

How does this extraReducers processing work?

我有多个 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

这是因为您创建了两个不同的异步 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 分配一个唯一的操作类型字符串前缀。