为什么 setState 不会重新渲染 React 页面

huangapple go评论62阅读模式
英文:

why setState doesn't rerender React page

问题

以下是您要求的代码部分的中文翻译:

// 我从 API GET 调用中获取了一些数据,将它们存储在 datas 变量中(因此不再是一个字符串),当用户选择一些筛选条件时,我想要删除其中的一些数据。我在控制台上看到数据发生变化,然后使用 setState 更新它们,但页面没有更新新的数据。

const [datas, setData] = useState(''); // 在这里定义了一个名为 datas 的状态变量

const handleClick = (event) => {
    console.log("删除数据"); // 打印日志以确认点击事件触发
    var newdata = datas; // 创建一个名为 newdata 的变量并将其设置为 datas 的引用
    newdata.splice(1, 1); // 使用 splice 方法删除数据(这会改变 newdata 和 datas)
    console.log(newdata); // 打印修改后的 newdata
    setData(newdata); // 使用 setData 更新状态变量 datas
};

我已经将代码部分翻译好了,没有包括其他内容。

英文:

I am having some datas from an API GET call,i store them in datas(so it's not longer a string) and i want to delete some of them when the user choose some filters. I see the data change on the console and setState them but the page doesn't update the new data.

const [datas, setData] = useState('');
const handleClick = (event) => {
    console.log("deleting")
    var newdata = datas
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

I used a new variable newdata because i saw that using the same variable data isn't recommended.
`

答案1

得分: 2

You are mutating the content of the array.

Do this in handleClick instead:

const handleClick = (event) => {
    console.log("deleting")
    // Create a copy of datas, do not modify the original array
    var newdata = [...datas]
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

That would solve it because you're creating a copy of the array with the spread operator ...

As a general rule, I'd always favor immutable array methods over mutable ones. You can check the docs for the methods and if it reads something like "changes the contents of an array", then the method is mutating the original array. Use methods that return a new copy of the array instead.

英文:

You are mutating the content of the array.

Do this in handleClick instead:

const handleClick = (event) => {
    console.log("deleting")
    // Create a copy of datas, do not modify the original array
    var newdata = [...datas]
    newdata.splice(1, 1);
    console.log(newdata)
    setData(newdata)
};

That would solve it because you're creating a copy of the array with the spread operator ...

As a general rule, I'd always favor immutable array methods over mutable ones. You can check the docs for the methods and if it reads something like "changes the contents of an array", then the method is mutating the original array. Use methods that return a new copy of the array instead.

huangapple
  • 本文由 发表于 2023年3月31日 19:20:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定