我正在构建一个简单的ToDoList应用程序。我使用React Hook获取列表。当我添加一个新的Todo或删除一个现有的Todo时,请求会发送并工作,但组件不会重新发送。我尝试了两种方法来解决问题1.异步函数(删除和添加(。在钩子外获取getToDoList,并在请求后调用它(post/delete(
useEffect(() => {
getToDoList();
}, []);
const getToDoList = async () => {
const result = await axios.get('http://localhost:1200/');
setToDoList(result.data);
};
const addNewTodo = async () => {
await axios.post('http://localhost:1200/create', {
item: newToDo.current.value
});
getToDoList();
};
const deleteToDo = async (id) => {
await axios.delete(`http://localhost:1200/delete?id=${id}`);
getToDoList();
};
2.在钩子内获取getToDoList,并给它2个deleteToDo/addNewToDo中更改的依赖项
const [add, setAdd] = useState(false);
const [remove, setRemove] = useState(false);
useEffect(() => {
const getToDoList = async () => {
const result = await axios.get('http://localhost:1200/');
setToDoList(result.data);
};
getToDoList();
}, [add, remove]);
const addNewTodo = async () => {
await axios.post('http://localhost:1200/create', {
item: newToDo.current.value
});
setAdd(!add);
};
const deleteToDo = async (id) => {
await axios.delete(`http://localhost:1200/delete?id=${id}`);
setRemove(!remove);
};
两者都不起作用。请告诉我哪里错了
JSX-
return (
<div>
<Jumbotron>
<Container>
<h1>Hello!</h1>
<p>This is a simple ToDoList created by Vadik</p>
</Container>
</Jumbotron>
<Container>
<Container>
<InputGroup>
<FormControl placeholder="What needs to be done" ref={newToDo}/>
</InputGroup>
<Button onClick={addNewTodo} variant="primary" size="sm">
Add new Todo
</Button>
</Container>
<Container className="cards">
<Card>
<ListGroup>
{toDoList.todos.map((elem) => <ListGroup.Item
key={elem._id}>{elem.item}<CloseButton onClick={() => deleteToDo(elem._id)}/> </ListGroup.Item>)}
</ListGroup>
</Card>
</Container>
</Container>
</div>
);
尝试以下代码。这应该行得通。在addTodo中,有两种方法,要么在发布成功后更新resultList,要么使用getList获取最新数据并更新resultList。两个都显示出来了。
function Example() {
const [resultList, setResult] = useState({todos: []});
useEffect(() => {
const todoList = getToDoList();
setResult(prev => todoList);
}, []);
const addTodo = async () => {
await axios.post('http://localhost:1200/create', {
item: newToDo.current.value
});
//Addition successful, hence update our resultList.
return setResult(prev => {
return {todos: [...prev.todos, {item: newToDo.current.value, id: prev.todos.length+1}]}
});
//Now since add api doesn't return a
//value call Get api again and update the todoList to render
//const todoList = getToDoList();
//setResult(prev => todoList);
};
const getToDoList = async () => {
const result = await axios.get('http://localhost:1200/');
return result.data;
};
return (
<div id='container'>
{resultList.todos.map(todo => <div>{todo.item}</div>
)}
<button onClick={addTodo}>Add</button>
</div>
)
}
问题是我没有向这些请求发送任何响应。在此处输入图像描述