这很简单,当您按下“添加”时,它应该添加(然后添加),而当您按下“删除”时,它应该弹出最后一个元素并重新呈现列表,但不是。我在某个地方犯错了吗?
import React, { useState, useEffect } from 'react';
const Test = () => {
const [list, setList] = useState([]);
const add = () => {
setList([list.length, ...list]);
}
const remove = () => {
list.pop();
setList(list);
}
useEffect(() => {
console.log(list)
}, [list])
return (<ul>
<button onClick={add}>add</button>
<button onClick={remove}>remove</button>
{list.map(el => <li>{el}</li>)}
</ul>)
}
export default Test;
更新: 实际上,它通过删除最后一个元素来更新状态,但是仅在按下“添加”按钮时才进行重新渲染
You need to set a new array in this case,
setList(list)
will not cause React to re-render because it's still the same array you're using.Try
setList([...list])
in yourremove
function.There's also an alternative to
pop
, and doesn't mutate the original variable:不建议修改状态本身,因为它是不可变的。
So instead using
.pop()
on the original state of the array, first I suggest to clone that one and remove the required element from there, then the result should passed tosetList()
function.请尝试以下操作:
考虑以下几点:
我希望这有帮助!