如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?
例如setState推的例子?
如何推动元素内useState数组反应钩子? 这是react状态下的老方法吗?还是一些新的东西?
例如setState推的例子?
当前回答
// 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
其他回答
如果你想推特定的索引,你可以这样做:
const handleAddAfterIndex = index => {
setTheArray(oldItems => {
const copyItems = [...oldItems];
const finalItems = [];
for (let i = 0; i < copyItems.length; i += 1) {
if (i === index) {
finalItems.push(copyItems[i]);
finalItems.push(newItem);
} else {
finalItems.push(copyItems[i]);
}
}
return finalItems;
});
};
setTheArray([…theArray newElement]);是最简单的答案,但要注意数组中项目的突变。使用数组项的深度克隆。
最推荐的方法是同时使用包装函数和展开运算符。例如,如果你像这样初始化了一个名为name的状态,
控制[names, setNames] = useState(]
你可以像这样推到这个数组,
setNames(names => [...names, newName])
希望这能有所帮助。
为了进一步展开, 这里有一些常见的例子。开始:
const [theArray, setTheArray] = useState(initialArray);
const [theObject, setTheObject] = useState(initialObject);
在数组的末尾推入元素
setTheArray(prevArray => [...prevArray, newValue])
在对象的末尾推/更新元素
setTheObject(prevState => ({ ...prevState, currentOrNewKey: newValue}));
在对象数组的末尾推/更新元素
setTheArray(prevState => [...prevState, {currentOrNewKey: newValue}]);
将元素推到数组对象的末尾
let specificArrayInObject = theObject.array.slice();
specificArrayInObject.push(newValue);
const newObj = { ...theObject, [event.target.name]: specificArrayInObject };
theObject(newObj);
这里也有一些实际的例子。 https://codesandbox.io/s/reacthooks-push-r991u
// 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