我有一个cartproductx
键的本地存储,其中包含对象数组
[
{"id":"001",
"productName":"Tesla",
"categories":"car",
"price":1000000,
"quantity": 1
},
{
"id":"002",
"productName":"Honda",
"categories":"motorcycle",
"price":10000,
"quantity": 2
},
{
"id":"003",
"productName":"BMW",
"categories":"car",
"price":1200000,
"quantity": 1
}
]
然后我执行从cartproductx[index].productName
获取值并设置为输入值的功能
import React, { useState } from 'react';
const carts = JSON.parse(localStorage.getItem("cartProductx"));
const GetData = () => {
const [data, setData] = useState(carts);
return (
<div>
<input
type="text"
placeholder=" product"
value={data[0].productName} //Tesla
onChange={e => setName(e.target.value)}
/>
<input
type="text"
placeholder="product"
value={data[1].productName} //Honda
onChange={e => setName(e.target.value)}
/>
<input
type="text"
placeholder="product"
value={data[2].productName} //BMW
onChange={e => setName(e.target.value)}
/>
</div>
)
}
问题是如何在没有硬编码的情况下一一重复输入形式和设置值?以及如何使用相同的键(“ cartproductx”)将更改后的值保存到本地存储中?
答案 0 :(得分:0)
您可以映射状态数据,并使用id
来使用handleChange
函数进行更改。
const carts = [
{
"id": "001",
"productName": "Tesla",
"categories": "car",
"price": 1000000,
"quantity": 1
},
{
"id": "002",
"productName": "Honda",
"categories": "motorcycle",
"price": 10000,
"quantity": 2
},
{
"id": "003",
"productName": "BMW",
"categories": "car",
"price": 1200000,
"quantity": 1
}
];
function App() {
const [data, setData] = React.useState(carts);
function handleChange(e, id) {
const { value } = e.target;
setData((prev) =>
prev.map((item) => {
if (item.id !== id) {
return item;
}
return { ...item, productName: value };
})
);
}
return (
<div>
{data.map((item) => (
<input
key={item.id}
type="text"
placeholder="product"
value={item.productName}
onChange={(e) => handleChange(e, item.id)}
/>
))}
{data.map((item) => (
<div key={item.id}>{item.productName}</div>
))}
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root" />
此外,如果您要使更改持久化,建议使用useEffect
从localStorage
读取数据,并再使用useEffect
进行设置。
function App() {
const [data, setData] = React.useState([]);
React.useEffect(() => {
const carts = JSON.parse(localStorage.getItem("cartProductx")) || [];
setData(carts);
}, [])
React.useEffect(() => {
localStorage.setItem("cartProductx", JSON.stringify(data));
}, [data]);
// rest of the code