问题
我正在开发一个网络应用程序功能,可以计算特定区域的隔热系数。您可以查看实时 Codesandbox 示例此处(这是带有单选按钮的第三个红色区域)。
我面临的问题是,当用户单击单选按钮时,我可以在控制台日志中看到状态正确更新。但是,当用户单击单选按钮时,页面右侧的“因子”框不会持续更新。我希望每次单击单选按钮时它都会更新。我怎样才能实现这个目标?
绝缘系数分量:
export const InsulFactor = () => {
// Pull in state from Zustand global store
const {
insul,
wellInsul,
poorlyInsul,
notInsul,
setInsul,
setWellInsul,
setPoorlyInsul,
setNotInsul,
} = useInsulFactorStore();
const handleInsulChange = () => {
setInsul(2);
};
const handleWellInsulChange = () => {
setWellInsul(4);
};
const handlePoorlyInsulChange = () => {
setPoorlyInsul(7);
};
const handleNotInsulChange = () => {
setNotInsul(8.5);
};
const getInsulFactor = () => {
if (insul) {
return insul;
}
if (wellInsul) {
return wellInsul;
}
if (poorlyInsul) {
return poorlyInsul;
}
if (notInsul) {
return notInsul;
}
return insul;
};
return (
<>
...
<Row>
<Col lg="4">
<CheckBox
heading="Insulated"
desc="Enclosed area with doors and windows in place."
id="insulated"
name="insulation"
checked={insul === 2}
onChange={handleInsulChange}
/>
</Col>
<Col lg="4">
<CheckBox
heading="Well Insulated"
desc="Sealed environment. Walls constructed but lacking insulation. Doors and windows shielded with plastic sheets or tarps."
id="well-insulated"
name="insulation"
checked={wellInsul === 4}
onChange={handleWellInsulChange}
/>
</Col>
<Col lg="4"> </Col>
</Row>
<Row>
<Col lg="4">
<CheckBox
heading="Poorly Insulated"
desc="Semi-enclosed area with numerous walls in place."
id="poorly-insulated"
name="insulation"
checked={poorlyInsul === 7.5}
onChange={handlePoorlyInsulChange}
/>
</Col>
<Col lg="4">
<CheckBox
heading="Not Insulated"
desc="Uncovered area with primary walls not yet built."
id="not-insulated"
name="insulation"
checked={notInsul === 8}
onChange={handleNotInsulChange}
/>
</Col>
<Col lg="4">
<Result heading="Factor" number={getInsulFactor()} />
</Col>
</Row>
...
</>
);
};
无线电组件:
export const CheckBox: React.FC<Props> = ({
heading,
desc,
id,
name,
onChange,
checked,
}) => {
return (
<>
<Form.Group>
<Form.Check
type="radio"
label=""
id={id}
name={name}
onChange={onChange}
defaultChecked={checked}
/>
<h3>{heading}</h3>
<p>{desc}</p>
</Form.Group>
</>
);
};
查看代码,我认为问题出在
useInsulFactorStore
您有多个级别的 insul
,然后它们彼此冲突,因为您的 getInsulFactor
函数将返回第一个真值。
相反,您应该将上下文更改为只有一个
insul/setInsul
状态,然后根据所选选项进行更新。
我在这里对 CodeSandBox 进行了一些编辑,以便您可以查看。