使用react-hook更新状态的正确方法是什么?
const [items, setItems]= useState([]];
const onChangeHandlers= (values)=> {
setItems({setItems:values})
}
const values = ['item1','item2','item3'];`
您必须具有更改值的功能
1: import React, { useState } from 'react';
2:
3: function Example() {
4: const [count, setCount] = useState(0);
5:
6: return (
7: <div>
8: <p>You clicked {count} times</p>
9: <button onClick={() => setCount(count + 1)}>
10: Click me
11: </button>
12: </div>
13: );
14: }
你的榜样
const [items, setItems] = useState([]);
const onChangeHandlers= (values)=> {
setItems(values)}};
在setState updater hook中更新状态时要记住的几个重要事项是
items
。正确的方法就是在调用普通函数时传递新值
const [items, setItems]= useState([]];
const onChangeHandlers= (values)=> {
setItems(values)
}
const values = ['item1','item2','item3'];
const [items, setItems] = useState([]);
const onChangeHandlers = values => {
setItems(prevState => ([
...items,
values
]);
};
const values = ['item1', 'item2', 'item3'];