在映射列表中递增反应计数器



我希望能够在映射的功能组件中使用单个onChange和handleIncrement来递增和递减值。

当单击函数运行时,它会使用相同的值更新所有列出的输入。

请问,我怎样才能让他们单独更新每个?

我仍然是菜鸟。

这是我的代码:

const [state, setState] = useState({
count: 0,
});
const handleChange = (e) => {
setState({
...state.count,
[e.target.name]: e.target.value,
});
};
const handleIncrement = () => {
setState((prevState) => {
return { count: prevState.count + 1 };
});
};
const listings = Consumables.map((list) => (
<Col lg={4}>
<Bounce up>
<Card
key={list.product}
style={{
width: "100%",
height: "25rem",
marginTop: "5%",
textAlign: "center",
}}
>
<Card.Header as="h3">{list.product}</Card.Header>
<Card.Body>
{list.productImage}
<br />
<br />
{list.description}
<br />
<br />
{list.weight}
<h5>Price: {list.price}</h5>
</Card.Body>
<Card.Footer>
<InputGroup className="mb-3">
<InputGroup.Prepend>
<Button variant="danger">-</Button>
</InputGroup.Prepend>
<FormControl
name={list.product}
type="text"
value={state.count}
onChange={handleChange}
/>
<InputGroup.Append>
<Button variant="success" onClick={handleIncrement}>
+
</Button>
</InputGroup.Append>
</InputGroup>
</Card.Footer>
</Card>
</Bounce>
</Col>
));

您只需要获取计数器的索引即可单独递增它:

import React, { Component } from "react";
import { render } from "react-dom";
const App = () => {
const [counters, setCounters] = React.useState([0, 0, 0, 0]);
const setCount = (index, newCounter) => {
const newCounters = Object.assign([], counters);
newCounters[index] = newCounter;
setCounters(newCounters);
};
return (
<div>
{counters.map((counter, index) => (
<Counter index={index} counter={counter} setCount={setCount} />
))}
</div>
);
};
const Counter = ({ index, counter, setCount }) => {
return (
<div>
Counter {index} = {counter}{" "}
<button onClick={() => setCount(index, counter + 1)}>Increment</button>
</div>
);
};
render(<App />, document.getElementById("root"));

我获取映射计数器的索引,并将其提供给组件,以便我可以轻松地指向状态中的正确计数器。更新仅使用一种将此索引作为参数的方法完成。

这是堆栈闪电战的重现

最新更新