我有一个如下列表
const[users,setUsers]=useState([]);
动态添加新用户并更新UI,我有如下函数
const addNewUser = newUser => {
setUsers(previousUsers=>{
//only add user if he has not been added
let existingUser = previousUsers.find((x)=>x.id===newUser.id);
if(!existingUser){
previousUsers.push(newUser);
}
return previousUsers;
});
}
不幸的是,上面的代码没有更新UI。这太奇怪了
我做错了什么?
我将在设置状态之外执行检查:
function addNewUser(newUser) {
const existingUser = users.find(user => user.id === newUser.id);
if (!existingUser) {
setUsers(prev => ([...prev, newUser]));
}
}
UI不是重新呈现的原因是因为状态值没有改变。如果你想在React State中使用数组或对象,你必须在修改它之前创建一个值的副本。你可以找到下面的基本范例:
const [todos, setTodos] = useState([]);
const handleAdd = (todo) => {
const newTodos = [...todos];
newTodos.push(todo);
setTodos(newTodos);
}