为什么以下反应功能组件无法正常工作?

这很简单,当您按下“添加”时,它应该添加(然后添加),而当您按下“删除”时,它应该弹出最后一个元素并重新呈现列表,但不是。我在某个地方犯错了吗?

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;

更新: 实际上,它通过删除最后一个元素来更新状态,但是仅在按下“添加”按钮时才进行重新渲染

评论
zsed
zsed

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 your remove function.

There's also an alternative to pop, and doesn't mutate the original variable:

  const remove = () => {
    const [removed, ...newList] = list
    setList(newList)
  }
点赞
评论
樱小桃~
樱小桃~

不建议修改状态本身,因为它是不可变的。

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 to setList() function.

请尝试以下操作:

const remove = () => {
    const copy = [...list];
    copy.pop();
    setList(copy);
}

考虑以下几点:

const list = [1,3,5,6,7];
const copy = [...list];
copy.pop();

console.log(list);
console.log(copy);

我希望这有帮助!

点赞
评论