我有一个从 Spring 引导后端加载条目的示例应用程序。然而,我的方法导致了一个我无法向自己解释的无限循环。
API.ts
class CommonApi extends BaseApi {
public loadEntries = () => this.get('http://localhost:8080/radars/development/entries') as Promise<any>;
}
条目切片.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;
我想我已经发现 entryiesSlice.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
时,它都会获取条目并在状态中创建一个新对象,该对象告诉 reactentries
已更新(它是一个具有新引用的新对象),它会重新运行useEffect
,再次调度getEntriesAction
,这...导致无限循环。