如何根据功能组件中的其他状态设置状态?
How can I set State based on other state in functional component?
我构建了一个简单的待办事项应用程序,其中包含一系列待办事项:
const todos = [description: "walk dog", done: false]
我使用了以下两种状态:
const [alltodos, handleTodos] = useState(todos);
const [opencount, countOpen] = useState(alltodos.length);
这是计算打开待办事项的函数:
const countTodos = () => {
const donetodos = alltodos.filter((item) => {
return !item.done;
});
countOpen(donetodos.length);
};
当我尝试添加新的待办事项时,我还想用 countTodos
函数更新 opencount
状态。
const submitTodo = (event) => {
event.preventDefault();
const data = {
description: todo,
done: false,
};
handleTodos([...alltodos, data]);
console.log(alltodos);
countTodos();
};
这没有按预期工作,当我 运行 console.log(alltodos)
时它会显示一个空数组。该函数本身有效,但它似乎有一个“延迟”,我猜是基于 useState
挂钩的异步性质。
我试图像这样将 countTodos
函数作为回调传递,因为我在基于 class 的组件中看到过类似的东西。
handleTodos([...alltodos, data], () => {
countTodos();
});
我收到以下错误:
Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().
我该如何解决这个问题?我根据另一个状态更新状态的最佳方法是什么?
我认为你应该使用 Effect,(在日志消息中明确说明)。这是一个例子:
useEffect(()=>{
const donetodos = alltodos.filter((item) => {
return !item.done;
});
countOpen(donetodos.length);
//countTodos();
},[alltodos]];
您可以参考文档:https://reactjs.org/docs/hooks-effect.html
这是一个例子:https://codesandbox.io/s/react-hooks-useeffect-forked-4sly8
我构建了一个简单的待办事项应用程序,其中包含一系列待办事项:
const todos = [description: "walk dog", done: false]
我使用了以下两种状态:
const [alltodos, handleTodos] = useState(todos);
const [opencount, countOpen] = useState(alltodos.length);
这是计算打开待办事项的函数:
const countTodos = () => {
const donetodos = alltodos.filter((item) => {
return !item.done;
});
countOpen(donetodos.length);
};
当我尝试添加新的待办事项时,我还想用 countTodos
函数更新 opencount
状态。
const submitTodo = (event) => {
event.preventDefault();
const data = {
description: todo,
done: false,
};
handleTodos([...alltodos, data]);
console.log(alltodos);
countTodos();
};
这没有按预期工作,当我 运行 console.log(alltodos)
时它会显示一个空数组。该函数本身有效,但它似乎有一个“延迟”,我猜是基于 useState
挂钩的异步性质。
我试图像这样将 countTodos
函数作为回调传递,因为我在基于 class 的组件中看到过类似的东西。
handleTodos([...alltodos, data], () => {
countTodos();
});
我收到以下错误:
Warning: State updates from the useState() and useReducer() Hooks don't support the second callback argument. To execute a side effect after rendering, declare it in the component body with useEffect().
我该如何解决这个问题?我根据另一个状态更新状态的最佳方法是什么?
我认为你应该使用 Effect,(在日志消息中明确说明)。这是一个例子:
useEffect(()=>{
const donetodos = alltodos.filter((item) => {
return !item.done;
});
countOpen(donetodos.length);
//countTodos();
},[alltodos]];
您可以参考文档:https://reactjs.org/docs/hooks-effect.html
这是一个例子:https://codesandbox.io/s/react-hooks-useeffect-forked-4sly8