Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React组件在状态更新时自动重新安装,为什么?_Javascript_Reactjs - Fatal编程技术网

Javascript React组件在状态更新时自动重新安装,为什么?

Javascript React组件在状态更新时自动重新安装,为什么?,javascript,reactjs,Javascript,Reactjs,我有一个父React.js组件,将状态和setter传递给子组件 每次子组件使用setter时,都会卸载和重新装载子组件。 我是个新手,不知道发生了什么 const useState=React.useState; 类myComponent扩展了React.Component{ intervalID=null; 组件安装{ 控制台安装; this.intervalID=setInterval=>{ this.props.setA{a:this.props.a.a+1}; }, 1000; }

我有一个父React.js组件,将状态和setter传递给子组件

每次子组件使用setter时,都会卸载和重新装载子组件。 我是个新手,不知道发生了什么

const useState=React.useState; 类myComponent扩展了React.Component{ intervalID=null; 组件安装{ 控制台安装; this.intervalID=setInterval=>{ this.props.setA{a:this.props.a.a+1}; }, 1000; } 组件将卸载{ clearIntervalthis.intervalID; } 渲染==>{ 回来 {this.props.a.a} ; }; } 功能应用程序{ 常量[activeStep]=useState0; const[a,setA]=useState{a:0}; //eslint禁用下一行反应/无多重复合 功能步骤页{ 如果0==0{ 回来 }否则{ 回来 } } 回来 ; } const rootElement=document.getElementByIdroot; ReactDOM.render,根元素; .App{ 字体系列:无衬线; 文本对齐:居中; }
问题在于,您正在通过在呈现函数中定义StepPage来创建组件的新实例

您可以重构StepPage组件,使其在render方法之外定义

function StepPage({ setA, a}) {
  if (0 === 0) {
    return <MyComponnent a={a} setA={setA} />;
  } else {
    return <MyComponnent />;
  }
}

export default function App() {
  const [activeStep] = useState(0);
  const [a, setA] = useState({ a: 0 });

  return (
    <div>
      <StepPage a={a} setA={setA} />
    </div>
  );
}
每次应用程序呈现时,都会重新定义示例中的StepPage

正常调用函数而不是将其用作React组件可以缓解此问题:

return (
  <div>
    {StepPage()}
  </div>
);

因为每次你的状态改变时你都在构建一个新的组件,为什么你不简单地重复返回@Mohamedayadi这是一个再现我问题的最小示例,在我的真实案例中,我使用StepPage进行条件渲染我正在为您编写一个解决方案,但我认为felixmosh已经完成了。我将您的场外代码沙盒链接移动到了一个现场堆栈片段。请记住,您必须在问题描述本身中包含a,任何非现场链接仅作为附加参考,不需要回答。在重新协商阶段,通过直接调用函数组件,react将假定树的这一部分已更改!使用jsx,react会更好地处理您的组件!在反转控制区!我已经更新了我的答案,使它更清楚和真实