#javascript #arrays #reactjs #object
Вопрос:
На самом деле, я застрял в какой-то точке, пожалуйста, взгляните на код один раз. Я хочу ввести пользовательский ввод в свой массив. Может ли кто-нибудь объяснить, почему это ошибка.
import React, { useState } from 'react';
function Cart() {
const [item, setItem] = useState({ cart: ['Corn', 'Potato'] });
const saveInput = (e) => {
setItem({ input: e.target.value });
};
const addNewItem = () => {
const { cart, input } = item;
cart.push(input);
return setItem({ cart: cart });
};
return (
<div>
<input type="text" onChange={saveInput} />
<button onClick={addNewItem}>Add Item</button>
<ol>
{item.cart.map((subItems, sIndex) => {
return <li key={sIndex}> {subItems}</li>;
})}
</ol>
</div>
);
}
export default Cart;
Комментарии:
1. Используйте отдельное состояние для отдельных задач. В вашем случае у вас должно быть состояние для ввода текста и состояние для товаров в вашей корзине
Ответ №1:
Вы можете использовать отдельные состояния. Один для ввода дескриптора, а другой для списка дескрипторов:
import React, { useState } from "react";
function Cart() {
const [item, setItem] = useState(["Corn", "Potato"]);
const [input, setInput] = useState("");
const saveInput = (e) => {
setInput(e.target.value);
};
const addNewItem = () => {
const copyCart = [...item];
copyCart.push(input);
setItem(copyCart);
setInput("");
};
return (
<div>
<input value={input} type="text" onChange={saveInput} />
<button onClick={addNewItem}>Add Item</button>
<ol>
{item.map((subItems, sIndex) => {
return <li key={sIndex}> {subItems}</li>;
})}
</ol>
</div>
);
}
export default function App() {
return <Cart />;
}
Вот полный пример:
Ответ №2:
Как и сказал Доминик, было бы гораздо эффективнее отделить свой штат.
Если вы хотите, чтобы ваш существующий код работал:
Изменить
setItem({ input: e.target.value });
Для:
setItem({ ...item, input: e.target.value });
Вы забыли распространить свое предыдущее состояние, прежде чем менять новое.
Ответ №3:
import React, { useState } from "react";
function Cart() {
const [item, setItem] = useState({ cart: ["Corn", "Potato"] });
// have a new state to hold the input value
const [inputValue, setInputValue] = useState("");
const saveInput = (e) => {
setInputValue(e.target.value);
};
const addNewItem = () => {
// spread the exisiting cardlist and append the newly added input value
setItem((existingCartList) => ({
cart: [...existingCartList.cart, inputValue]
}));
// clear the input once it is added to card list
// so we can prevent the user from manually clearing it
setInputValue("");
};
return (
<div>
{/* need to pass the inputValue state to the value attribute
which makes the input a controlled component */}
<input type="text" value={inputValue} onChange={saveInput} />
<button onClick={addNewItem}>Add Item</button>
<ol>
{item.cart.map((subItems, sIndex) => {
return <li key={sIndex}> {subItems}</li>;
})}
</ol>
</div>
);
}
export default Cart;
Ссылка