[英]How to save the response info in the Redux state after fetch into useEffect hook?
我有以下情況:
export default function Names() { const dispatch = useDispatch(); const [names, setNames] = useState([]); const stateNames = useSelector(state => state.names); const fetchNames = async () => { try { const response = await nameService.getNames(); dispatch(initNames(response.body)); setNames(response.body); } catch (error) { console.error('Fetch Names: ', error); } }; useEffect(() => { fetchNames(); }, []); return ( { names.map((name, index) => ( <Tab label={ budget.label} key={index}/> )) } ); }
當我的組件在瀏覽器控制台中呈現時,我收到一條警告:“React Hook useEffect 缺少依賴項:‘fetchBudgets’。要么包含它,要么刪除依賴項數組 react-hooks / exhaustive-deps”。 如果我在 Redux state 中注釋我寫名字的行,則不會出現警告。 我需要 state 中的名稱列表,以便在從外部將新名稱寫入列表時更新列表。
export default function AddNameComponent() {
const dispatch = useDispatch();
const [label, setLabel] = useState('');
const [description, setDescription] = useState('');
const onLabelChange = (event) => { setLabel(event.target.value); };
const onDescriptionChange = (event) => { setDescription(event.target.value); };
const handleSubmit = async (event) => {
try {
event.preventDefault();
const newName = {
label: label
description: description
};
const answer = await budgetService.postNewName(newName);
dispatch(add(answer.body)); // Adding new Name in to Redux state.names
} catch (error) {
setErrorMessage(error.message);
console.error('Create Name: ', error);
}
};
return (
<div>
// Create name form
</div>
)
}
這就是一切的運作方式,但我不明白為什么我會收到警告。 我試圖用 useEffect 的依賴項向數組添加一個標志。 我試圖通過父組件傳遞 function 'fetchNames' - 在 props 中並將其添加為依賴項,但它被執行了兩次......請你指教!
這只是一個 eslint 警告,因此您不必修復它。 但基本上在useEffect
function 中使用的任何變量都應該包含在依賴項數組中。 否則,即使 function fetchBudgets
發生變化,效果也永遠不會重新運行。
它期待你的鈎子看起來像
useEffect(() => {
fetchBudgets();
}, [fetchBudgets]);
效果將在組件安裝時運行一次,並在fetchBudgets
function 更改(可能永遠不會)時再次運行。
如果它執行了不止一次,這意味着fetchBudgets
已經改變,你應該試着弄清楚我們在哪里以及為什么它被重新定義了。 也許它需要記憶?
Here are the docs on putting functions in the dependency array。
感謝您的關注。 我嘗試了很多選擇,最后找到了一個解決方案。
useEffect(() => {
async function fetchNames() {
const response = await nameService.getNames();
dispatch(init(response.body));
setNames(response.body);
}
fetchNames();
}, [dispatch, props]);
我將 'props' 放在一組依賴項中以執行一次 useEffect。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.