简体   繁体   English

在数组中添加多个值

[英]Add multiple value in array

In my application, in React i have next situation: I have input where i add different values when i click on save .在我的应用程序中,在 React 中我有下一个情况:我输入了当我点击save时添加不同值的地方。 The value from input is converted from string to array.输入的值从字符串转换为数组。 So, first time i added a text, i clicked save, and i have 1 value in array.所以,我第一次添加文本时,我点击了保存,我在数组中有 1 个值。 Second time, i add another text, i click, on save and the first value is changed by second.第二次,我在保存时添加另一个文本,单击,第一个值被第二个更改。 I store value in this state:我将值存储在这个 state 中:

 const [value, setValue] = useState([here comes my value]);

I want to concat the value one after one and i did:我想一个接一个地连接值,我做到了:

 useEffect(()=> { setAllValues([...value, value]) }, [value])

..but this does't work. ..但这不起作用。 How to store all values in one array?如何将所有值存储在一个数组中?

Use the functional form of setState :使用setState函数形式

 setAllValues(prevValue => [...prevValue, newValue])

To perform that operation you would need two states要执行该操作,您需要两种状态

// one state for array
const [valueArray, setValueArray] = useState([here comes my value]);

// and another state for string
const [value, setValue] = useState('');


// then onSave function
const onSave = () => {
  setValueArray([  ...valueArray, value ]);
  setValue('');
}

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

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