react-redux:调度时无限循环

react-redux: infinite loop on dispatch

我有一个从 Spring 引导后端加载条目的示例应用程序。然而,我的方法导致了一个我无法向自己解释的无限循环。

api.ts

class CommonApi extends BaseApi {
  public loadEntries = () => this.get('http://localhost:8080/radars/development/entries') as Promise<any>;
}

entriesSlice.ts

interface EntriesState {
    map: {}
}

const initialState: EntriesState = {
    map: {}
};

export const entriesSlice = createSlice({
    name: 'entries',
    initialState,
    reducers: {
        getEntries: (state, action: PayloadAction<any>) => {
            state.map = action.payload;
        },
    },
});

export const { getEntries } = entriesSlice.actions;

export const getEntriesAction = (): AppThunk => dispatch => {
    return commonApi.loadEntries().then(payload => {
        const newPayload: any[] = [];

        payload.map((entry: any) => {
            return newPayload.push({
                label: entry.label,
                quadrant: toSegment(entry.category),
                ring: toRing(entry.status)
            })
        })

        dispatch(getEntries(newPayload));
    }).catch(err => {
        console.error('error: ', err)
    })
};

export const entriesObject = (state: RootState) => state.entries.map;

export default entriesSlice.reducer;

我想我已经发现 entriesSlice.ts 中的这一行导致错误,但我不知道为什么:

state.map = action.payload;

App.tsx

import { entriesObject, getEntriesAction } from "../../features/entries/entriesSlice";
import { config1Object, getConfig1Action } from "../../features/config1/config1Slice";

function App() {
  const config1 = useSelector(config1Object) as any;
  const entries = useSelector(entriesObject) as any;
  const dispatch = useDispatch();
  const [value, setValue] = useState(0);

  useEffect(() => {
    dispatch(getConfig1Action());
    dispatch(getEntriesAction());
  }, [config1, entries, dispatch]);

  return (
    <Container>
      <TabPanel value={value} index={0}>
        <Chart config={config1} entries={entries} />
      </TabPanel>
    </Container>
  );
}

我做错了什么?

你有 entries 作为你的 useEffect 的依赖 - 每次 getEntriesAction 被分派它获取条目并在状态中创建一个新对象,它告诉反应 entries 已更新(它是一个带有新引用的新对象),它重新运行 useEffect,它再次调度 getEntriesAction,这...导致无限循环。