【发布时间】:2021-07-01 21:44:41
【问题描述】:
为了不改变我的 React 组件中的状态,我想出了这个可行的解决方案。
但是,它似乎有我想摆脱的代码气味,即我将传入部分(JavaScript 对象)定义为一个虚拟变量section2,然后我将其用作默认值来设置我的状态变量section 然后我使用解构赋值使其不发生变异。
有没有办法在没有虚拟变量的情况下做到这一点?
interface ICurriculumSectionProps {
section2: ICurriculumSection;
searchText: string;
sectionIndex: number;
}
function CurriculumSection(props: ICurriculumSectionProps) {
const { section2, searchText, sectionIndex } = props;
const [section, setSection] = useState(section2);
const toggleContent = () => {
setSection({...section, showContent: !section.showContent});
};
【问题讨论】:
-
为什么
showContent不只是一个单独的useState?这不仅会让一切变得更简单吗?