【问题标题】:How to not mutate a prop variable used as state in a React component without a dummy variable?如何在没有虚拟变量的情况下不改变 React 组件中用作状态的 prop 变量?
【发布时间】: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?这不仅会让一切变得更简单吗?

标签: reactjs state


【解决方案1】:

这是一个道具。在将值从父级传递给子级时,道具经常用作初始状态。你的所作所为一点都不奇怪。

我想如果你想通过简单地使用 props 来删除 section2 变量:

const [section, setSection] = useState(props.section2);

但这仍然与您的原始代码相当,在我看来一点也不臭。

您还可以考虑将 prop 定义为 initialSection 以使事情更清晰。

function CurriculumSection({
  initialSection,
  searchText,
  searchIndex,
}: ICurriculumSectionProps) {
  const [section, setSection] = useState(initialSection);

确实在这里看起来有点奇怪的一件事是

setSection({...section, showContent: !section.showContent});

除非整个有状态的section 需要成为一个有凝聚力的对象以供以后使用的东西,否则将showContent 拆分为不同的变量会更有意义,例如React recommends

const [showContent, setShowContent] = useState(props.initialSection.showContent);

const toggleContent = () => {
    setShowContent(!showContent);
};

(但如果您必须将它们放在一个对象中,那么您当前的方法是有意义的)

【讨论】:

  • 是的,我在这个组件中显示了section 对象的许多属性。很高兴听到使用道具作为状态变量的初始值并不是某种反模式,因为它肯定很有用。 initialSection 这个名字很有意义。谢谢。
猜你喜欢
  • 2019-09-02
  • 2021-01-11
  • 1970-01-01
  • 2023-03-20
  • 2023-02-09
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
相关资源
最近更新 更多