javascript 使用 Hooks 在 React 中更新数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54770234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:26:58  来源:igfitidea点击:

Updating an array in React using Hooks

javascriptreactjsreact-hooks

提问by Jithin Ks

I'm trying to figure out the working of React Hook API. I'm trying to add a number to a list. The code that I commented, i.e myArray.push... doesn't seem to perform the operation, though the code below it is working fine. Why is it so?

我试图弄清楚 React Hook API 的工作原理。我正在尝试向列表中添加一个数字。我评论的代码,即 myArray.push... 似乎没有执行操作,尽管它下面的代码工作正常。为什么会这样?

import React, {useState} from 'react'

export default () => {

  const [myArray, setArray] = useState([1,2,3])

  return (
    <div>
      {myArray.map((item=>{

        return <li>{item}</li>

      }))}
      <button onClick = {()=>{

        // myArray.push(myArray[myArray.length-1]+1)
        // setArray(myArray)

        setArray([...myArray, myArray[myArray.length-1]+1])

      }}>Add</button>
    </div>
  )
}

回答by K..

I'd would recommend to use useReducerfor anything more complicated than a single value.

我建议将其useReducer用于比单个值更复杂的任何事物。

function App() {
  const [input, setInput] = useState(0);

  const [myArray, dispatch] = useReducer((myArray, { type, value }) => {
    switch (type) {
      case "add":
        return [...myArray, value];
      case "remove":
        return myArray.filter((_, index) => index !== value);
      default:
        return myArray;
    }
  }, [1, 2, 3]);

  return (
    <div>
      <input value={input} onInput={e => setInput(e.target.value)} />
      <button onClick={() => dispatch({ type: "add", value: input})}>
        Add
      </button>

      {myArray.map((item, index) => (
        <div>
          <h2>
            {item}
            <button onClick={() => dispatch({ type: "remove", value: index })}>
              Remove
            </button>
          </h2>
        </div>
      ))}
    </div>
  );
}

回答by Shubham Khatri

You aren't mutating the array in the commenting code and hence when you try to setState, hooks internally check that the same state is being passed due to reference not updating for myArray and hence, won't trigger a re-render again.

您没有在注释代码中改变数组,因此当您尝试 setState 时,钩子会在内部检查是否由于引用未更新 myArray 而传递了相同的状态,因此不会再次触发重新渲染。

However in the working code, you are creating a new array instance and hence the update is working correctly

但是在工作代码中,您正在创建一个新的数组实例,因此更新工作正常