我尝试使用钩子并实现一个自定义钩子,以在每次发送给API的更新后处理我的数据提取。
但是,我的自定义钩子并不会像我想要的那样触发更改。必须单击“删除”两次才能重新渲染。注意:我从这段代码中删除了一些函数,因为它们与问题无关。
import React, { useState, useEffect } from "react"
import {Trash} from 'react-bootstrap-icons'
import InlineEdit from 'react-ions/lib/components/InlineEdit'
function Board(){
const [render, setRender] = useState(false)
const [boards, setBoards] = useState([]);
const [isEditing, setEdit] = useState(false)
const [value, setValue] = useState("")
const[newValue, setNewValue] = useState("")
const [error, setError] = useState("")
function useAsyncHook(setState, trigger) {
const [result] = useState([]);
const [loading, setLoading] = useState("false");
useEffect(() => {
async function fetchList() {
try {
setLoading("true");
const response = await fetch(
`http://localhost:8080/api/boards`
);
const json = await response.json();
setState(json)
} catch (error) {
//console.log(error)
setLoading("null");
}
}
fetchList()
}, [trigger]);
return [result, loading];
}
useAsyncHook(setBoards, render)
const handleDelete = (id) => {
console.log("delete clicked")
setLoading(true);
fetch(`http://localhost:8080/api/boards/` + id, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
},
})
setRender (!render)
}
return(
<div>
<ul>
{boards.map(board => (
<li key={board.id}>
<InlineEdit value={board.size} isEditing={isEditing} changeCallback={(event)=>handleSave (event, board.id)} />
<Trash onClick={()=>handleDelete(board.id)}/>
</li>
</ul>
</div>
);
}
export default Board
答案 0 :(得分:1)
选项1:
也许您想要一个钩子,告诉您何时取板,对吧?例如:
const [auxToFetchBoard, setAuxToFetchBoard] = useState(false);
然后,在useEffect
中,每次钩子更改时都执行函数fetchBoard
:
useEffect(fetchBoard, [auxToFetchBoard]);
最后,在您的handleDelete
函数中,如果删除请求正确返回,则必须更新auxToFetchBoard
。像这样:
const handleDelete = (id) => {
setIsLoading(true);
setError("");
fetch(yourURL, yourOptions)
.then(res => {
// check if response is correct and
setIsLoading(false);
setAuxToFetchBoard(!auxToFetchBoard);
})
.catch(() => {
setIsLoading(false);
setError("Error while deleting stuff");
});
};
注意:我更改了isLoading
和setIsLoading
的名称,因为它们更明确。
选项2:
您可以更新板(而不是一次又一次地获取板)(在这种情况下,代码将位于handleDelete
函数内的第8行中)。
希望有帮助。