简体   繁体   English

如何使用反应钩子将新值推送到当前数组中?

[英]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?如何解决这个问题? 在此处输入图片说明

react will not rerender if setState return the same state that was before.如果 setState 返回与之前相同的状态,react 将不会重新渲染。 when you use the push method you mutate the state object.当您使用 push 方法时,您会改变状态对象。 instead create a new array with the new item.而是使用新项目创建一个新数组。

always update your state in immutable way.始终以不可变的方式更新您的状态。

in your case:在你的情况下:

onClick={() => {
   setArr((prevArr) => ([...prevArr, prevArr.length + 1]));
}}

I'm not too sure what values you want to push into your array, but the root cause of your issue is you're mutating the stateful array then attempting to update it (on lines 22 and 23).我不太确定您想将哪些值推送到数组中,但问题的根本原因是您正在改变有状态数组,然后尝试更新它(第 22 行和第 23 行)。

Remove your arr.push(0) on line 22 and replace line 23 with:删除第 22 行的arr.push(0)并将第 23 行替换为:

setArr(prevValues => [...prevValues, 0])

and you will see the real time state update.您将看到实时状态更新。 In this example I just added 0 to the array for each button click, you can change that to whatever value you want to push into the array.在这个例子中,我只是为每次按钮点击将 0 添加到数组中,您可以将其更改为您想要推送到数组中的任何值。 Remember to never mutate a stateful array, hopefully that helps!记住永远不要改变有状态的数组,希望这会有所帮助!

reference of new array is stored in old array variable新数组的引用存储在旧数组变量中

const [arr, setArr] = useState([1,2,3])
setArr([...arr,1])

The setArr should contain an arrow function to access the prevState,so as to avoid incorrect / outdated state snapshot since react schedules State updates, it doesn't perform them instantly setArr 应该包含一个箭头函数来访问 prevState,以避免不正确/过时的状态快照,因为 react 调度状态更新,它不会立即执行它们

const [arr, setArr] = useState([1,2,3]);
setArr(prevArr=>{
return [...prevArr,4]
});

if it is an object, and you want to change a single key's value.如果它是一个对象,并且您想更改单个键的值。

const [userInput, setUserInput] = useState({
        enteredTitle: '',
        enteredAmount: '',
        enteredDate: ''
    });
setUserInput((prevUserInput)=>{
          return {
            ...prevUserInput,
            enteredTitle: "Something Else"
        }
})
//for copying the whole object, and only changing enteredTitle's value in it

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM