javascript - How to push a new value into the current array using the react hooks?
问题描述
This is the source code.
import React, { useState } from "react"
import ReactDOM from "react-dom"
import "./styles.css"
function App() {
const [arr, setArr] = useState([1,2,3])
return (
<div className="App">
<h1>
Length:{arr.length}
</h1>
<h2>
Values:
{arr.map(i=>i+',')}
</h2>
<button
onClick={() => {
arr.push(0) //my wrong code
setArr(arr) //my wrong code
// setArr(prevValues => [...prevValues, 0])//Alex K's answer
// setArr(prevArr => [...prevArr, prevArr.length + 1]); //rotemls98's answer
// setArr([...arr,1])//venkateshwar's answer
console.log(arr);
}}
>
push
</button>
</div>
);
}
const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)
What I want to do is to push a new value into the current array and update length and values when I click the push button.
It printed to the console normally, but not change the display.
How to resolve this?
解决方案
如果 setState 返回与之前相同的状态,react 将不会重新渲染。当您使用 push 方法时,您会改变状态对象。而是使用新项目创建一个新数组。
始终以不可变的方式更新您的状态。
在你的情况下:
onClick={() => {
setArr((prevArr) => ([...prevArr, prevArr.length + 1]));
}}
推荐阅读
- docker - 你能让 fluent-ffmpeg 使用在 Docker 容器中运行的 ffmpeg 的副本吗?
- javascript - 调整窗口大小时更改工具提示的位置
- android - adjustViewBounds 究竟对图像输出做了什么?
- plotly - 如何更改 plotly 3d 图中的轴标签?
- jenkins - 在詹金斯控制台中隐藏 bash 脚本
- mysql - 查询左连接取数据问题-Mysql
- git - 当另一个分支发生变化时,为什么将它称为重新定位到 master 上?
- javascript - 奇怪的 javascript 和 web 服务器请求行为,托管新的 OpenCart 安装
- prestashop - PS 1.7 - 验证注册表单中的电子邮件
- python - 如何仅针对字典的某些条目而不是全部处理 KeyError?