![](/img/trans.png)
[英]React - How to update the state in useEffect without causing an infinite loop?
[英]Why useEffect in Redux state is causing infinite loop:
當我從 api 獲取項目列表時遇到此問題。axios 在操作中發出獲取請求。 發送到 reducer 並在 state 中進行更改。所以我希望列表僅在用戶添加、刪除或更新項目時更新。 我正在使用 useEffect 掛鈎將列表作為依賴項傳遞給更改,但它只是在無限循環中獲取,極大地影響了性能。
動作創造者:
import axios from "axios";
const BASE_URL = "https://localhost:5001/api";
export function getList() {
return (dispacth) => {
return axios.get(`${BASE_URL}/billingCycles`).then((res) =>
dispacth({
type: "BILLING_CYCLES_FETCHED",
payload: res.data,
})
);
};
}
減速器:
const INITIAL_STATE = { list: [], billingCycle: {}, credits: [], debts: [] };
// eslint-disable-next-line import/no-anonymous-default-export
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
case "BILLING_CYCLES_FETCHED":
return { ...state, list: action.payload };
..MORE CASES BELOW...
}
}
列表組件:
import React, { useEffect } from "react";
import ListItem from "./ListItem";
import { getList } from "../../store/actions/billingCycleActions";
import { setCreate } from "../../store/actions/modalActions";
import { useDispatch, useSelector } from "react-redux";
function List() {
const dispatch = useDispatch();
const billingCycles = useSelector((state) => state.billingCycles.list);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => dispatch(getList()), [billingCycles]);
return (
<div>
<div className="mb-3 d-flex justify-content-lg-start">
<button
className="btn btn-success"
onClick={() => dispatch(setCreate(true))}
>
<i className="fas fa-plus m-1"></i>
Novo ciclo!
</button>
</div>
<table className="table table-hover border ">
<thead className="border">
<tr>
<th>Nome</th>
<th>Mês</th>
<th>Ano</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
{billingCycles &&
billingCycles
.map((el) => {
return (
<ListItem
index={el.id}
name={el.name}
month={el.month}
year={el.year}
/>
);
})
.reverse()}
</tbody>
</table>
</div>
);
}
export default List;
如果只需要在初始渲染中獲取列表,請將依賴項數組留空,這樣它只會調用一次
useEffect(() => dispatch(getList()), []);
否則,您的提取將改變billingCycles
,導致重新渲染,最終導致無限循環。
更多關於這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.