Javascript React Hooks (useState) 中的推送方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54676966/
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-08-23 05:14:15  来源:igfitidea点击:

Push method in React Hooks (useState)?

javascriptreactjsreact-hooks

提问by Milosh N.

How to push element inside useState array React hook? Is that as an old method in react state? Or something new?

如何将元素推送到 useState 数组 React 钩子中?这是作为反应状态的旧方法吗?或者有什么新东西?

E.g. setState push example?

例如setState 推送示例

回答by T.J. Crowder

When you use useState, you can get an update method for the state item:

使用时useState,可以获得状态项的更新方法:

const [theArray, setTheArray] = useState(initialArray);

then, when you want to add a new element, you use that function and pass in the new array or a function that will create the new array. Normally the latter, since state updates are asynchronous and sometimes batched:

然后,当您想要添加新元素时,您可以使用该函数并传入新数组或将创建新数组的函数。通常是后者,因为状态更新是异步的,有时是批处理的:

setTheArray(oldArray => [...oldArray, newElement]);

Sometimes you can get away without using that callback form, if you onlyupdate the array in handlers for certain specific user events like click(but not like mousemove):

有时,如果您针对某些特定用户事件click(例如(但不是 like mousemove))更新处理程序中的数组,则无需使用该回调表单就可以逃脱:

setTheArray([...theArray, newElement]);

The events for which React ensures that rendering is flushed are the "discrete events" listed here.

React 确保刷新渲染的事件是此处列出的“离散事件” 。

Live Example (passing a callback into setTheArray):

实时示例(将回调传递到setTheArray):

const {useState, useCallback} = React;
function Example() {
    const [theArray, setTheArray] = useState([]);
    const addEntryClick = () => {
        setTheArray(oldArray => [...oldArray, `Entry ${oldArray.length}`]);
    };
    return [
        <input type="button" onClick={addEntryClick} value="Add" />,
        <div>{theArray.map(entry =>
          <div>{entry}</div>
        )}
        </div>
    ];
}

ReactDOM.render(
    <Example />,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

Because the only update to theArrayin there is the one in a clickevent (one of the "discrete" events), I could get away with a direct update in addEntry:

因为theArray那里唯一的更新是click事件中的一个(“离散”事件之一),所以我可以直接更新addEntry

const {useState, useCallback} = React;
function Example() {
    const [theArray, setTheArray] = useState([]);
    const addEntryClick = () => {
        setTheArray([...theArray, `Entry ${theArray.length}`]);
    };
    return [
        <input type="button" onClick={addEntryClick} value="Add" />,
        <div>{theArray.map(entry =>
          <div>{entry}</div>
        )}
        </div>
    ];
}

ReactDOM.render(
    <Example />,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>

回答by Elia Ahadi

To expand a little further, here are some common examples. Starting with:

为了进一步扩展,这里有一些常见的例子。从...开始:

const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);

Push element at end of array

在数组末尾推送元素

setTheArray(prevArray => [...prevArray, newValue])

Push/update element at end of object

在对象末尾推送/更新元素

setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));

Push/update element at end of array of objects

在对象数组的末尾推送/更新元素

setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);

Push element at end of object of arrays

在数组对象的末尾推送元素

setTheObject(prevState => ({...prevState, currentKey: [...prevState.currentKey, newValue]}));

Here are some working examples too. https://codesandbox.io/s/reacthooks-push-r991u

这里也有一些工作示例。 https://codesandbox.io/s/reacthooks-push-r991u

回答by fard

The same way you do it with "normal" state in React class components.

与在 React 类组件中使用“正常”状态执行此操作的方式相同。

example:

例子:

function App() {
  const [state, setState] = useState([]);

  return (
    <div>
      <p>You clicked {state.join(" and ")}</p>
      //destructuring
      <button onClick={() => setState([...state, "again"])}>Click me</button>
      //old way
      <button onClick={() => setState(state.concat("again"))}>Click me</button>
    </div>
  );
}

回答by Shivang Gupta

setTheArray([...theArray, newElement]);is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.

setTheArray([...theArray, newElement]);是最简单的答案,但要小心theArray中项目的突变。使用数组项的深度克隆。

回答by Adarsh Pawar

// Save search term state to React Hooks with spread operator and wrapper function

// Using .concat(), no wrapper function (not recommended)
setSearches(searches.concat(query))

// Using .concat(), wrapper function (recommended)
setSearches(searches => searches.concat(query))

// Spread operator, no wrapper function (not recommended)
setSearches([...searches, query])

// Spread operator, wrapper function (recommended)
setSearches(searches => [...searches, query])

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc

https://medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc