const [number, setNumber] = React.useState({})
The way Im doing it below does not work:
setNumber(prevNumber => ({
...prevNumber,
[num]: (prevNumber[num] + 1) || 0,
}))
The only way to get it to work is when i define the properties as below:
const [number, setNumber] = React.useState({
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
})
I dont know how many properties I will have (maybe 1-5 or 1-10 for example) and dont want to pre define all of them. Any help would be great. Thank you.
Update: 'full code':
// what i get is:{4: 4, 5: 1}
//what I wanted and get if i have initialState is: {1: 0, 2: 0, 3: 0, 4: 4, 5: 1}
const reviews = [
{ title: "movie1", rating: 4 },
{ title: "movie2", rating: 5 },
{ title: "movie3", rating: 4 },
{ title: "movie4", rating: 4 },
{ title: "movie4", rating: 4 }
];
function App() {
const [number, setNumber] = useState({ 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 });
const func = (num) => {
setNumber((prevNumber) => ({
...prevNumber,
[num]: (prevNumber[num] || 0) + 1 || 0
}));
};
const getNumbers = () => {
return reviews.map((review) => {
func(review.rating);
});
};
console.log("number: ", number);
return (
<div>
<button onClick={getNumbers}>helo</button>
</div>
);
}
question from:
https://stackoverflow.com/questions/65940727/react-how-to-update-state-with-dynamic-properties-without-defining-it-in-state 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…