useState 未在 array.map() 内更新。响应式JS
useState is not updating inside array.map(). ReactJS
我正在尝试通过在 array.map 中使用 useState 添加数组的值,但这些值没有更新
function App() {
const [ingredients, setIngredients] = useState([]);
const getIngredients = (data) => {
data.map((item, i) => {
console.log(data[i]);
setIngredients([...ingredients, data[i]]);
// setIngredients([...ingredients, item]); <- Also doesnt work
console.log(ingredients);
});
Console.log(数据)
(26) ["Product", "Information↵NUTELLA", "HAZELNUT", "SPREAD", "↵Total:", "↵aty:", "↵BARILLA", "SPAGHETTI", "Z↵Total:", "↵CLASSICO", "CRMY", "ALFERO", "DI", "ROMA", "PENNE", "RIGATE", "PASTA", "↵Order", "Summary↵item", "Subtotat", "↵Sales", "Tax", "Total:", "", "↵", Array(0)]
console.log(成分);
[]
console.log(项);
Lists out all the items one after the other
setState 是异步的,因此它不能保证更新之前的状态,因此将一个函数传递给 setState 以使其工作。
setIngredients((ingredients) => [...ingredients, data[i]]);
我正在尝试通过在 array.map 中使用 useState 添加数组的值,但这些值没有更新
function App() {
const [ingredients, setIngredients] = useState([]);
const getIngredients = (data) => {
data.map((item, i) => {
console.log(data[i]);
setIngredients([...ingredients, data[i]]);
// setIngredients([...ingredients, item]); <- Also doesnt work
console.log(ingredients);
});
Console.log(数据)
(26) ["Product", "Information↵NUTELLA", "HAZELNUT", "SPREAD", "↵Total:", "↵aty:", "↵BARILLA", "SPAGHETTI", "Z↵Total:", "↵CLASSICO", "CRMY", "ALFERO", "DI", "ROMA", "PENNE", "RIGATE", "PASTA", "↵Order", "Summary↵item", "Subtotat", "↵Sales", "Tax", "Total:", "", "↵", Array(0)]
console.log(成分);
[]
console.log(项);
Lists out all the items one after the other
setState 是异步的,因此它不能保证更新之前的状态,因此将一个函数传递给 setState 以使其工作。
setIngredients((ingredients) => [...ingredients, data[i]]);