如果密钥存在,如何添加到状态或以其他方式替换状态



我有几个单选按钮,我想通过第一次初始点击设置状态来生成动态状态,然后在将状态连接到当前状态或用新值替换键(如果键已经存在(后每次点击。

我自己尝试过,所以如果它看起来一点都不对,请原谅我自己。

这是我尝试做的一个例子。

import React, { useState } from "react";
import { FormGroup, CustomInput } from "reactstrap";
import UniqueString from "unique-string";
function Ratings({ parentCheckedGood, parentCheckedNA, Question }) {
//initializing empty state object
const [state, setState] = useState({});
//Here is where I am stuck, with each click after the first I should concatenate or 
//replace
const handleChange = (e) => {
const { name, value } = e.target;
if (name in state) {
setState(...state, { name: value });
} else {
setState(...state, {
name: value,
});
}
};
console.log(state);
const string = UniqueString();
return (
<div>
<FormGroup required>
<div onChange={handleChange}>
<CustomInput
// checked={parentCheckedGood}
type="radio"
id={string + "1"}
name={Question}
value="Good"
label="Good"
/>
<CustomInput
type="radio"
id={string + "2"}
name={Question}
value="Fair"
label="Fair"
/>
<CustomInput
type="radio"
id={string + "3"}
name={Question}
value="Poor"
label="Poor"
/>
<CustomInput
// checked={parentCheckedNA}
name={Question}
type="radio"
id={string + "4"}
value="N/A"
label="N/A"
/>
</div>
</FormGroup>
</div>
);
}
export default Ratings;

这些收音机按钮让我很有钱。。干杯

使用setState的函数格式,您就可以接近语法:

const handleChange = (e) => {
const { name, value } = e.target;
setState(state => ({ ...state, [name]: value }))
};

最新更新