react组件渲染方法无缘无故被调用两次 [英] react component render method being called twice for no reason

查看:125
本文介绍了react组件渲染方法无缘无故被调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import './App.css';
import SolarSystem from './components/solarSystem/solarSystem';

class  App extends React.Component {
  componentDidMount(){
    console.log("mounting");
  }

  componentDidUpdate(){
    console.log("updating");
  }
  //const [SSVisibility, setSSVisibility] = useState(true);
  render(){ 
    console.log("rendering app");
    return (
    <div className="App">ssssssssssssssssssssssssssssssss
    {/*   <SolarSystem isShowing={"yolo"} toggle={"polo"}></SolarSystem> */}
    </div>
  );
}
}
export default App; 

通过这个简单的代码,我的render方法被调用了两次.而且我不明白为什么

With this simple code, my render method is being called twice. And i cant understand why

推荐答案

由于严格的模式,下面的代码没有演示它,因为SO会在生产设置为true的情况下构建它(我认为).

It is because of strict mode, code below doesn't demonstrate it because SO will build it with production set true (I think).

class Strict extends React.Component {
  componentDidMount() {
    console.log('mounting strict');
  }

  componentDidUpdate() {
    console.log('updating');
  }
  //const [SSVisibility, setSSVisibility] = useState(true);
  render() {
    console.log('rendering strict');
    return (
      <div className="App">
        {/*   <SolarSystem isShowing={"yolo"} toggle={"polo"}></SolarSystem> */}
      </div>
    );
  }
}
class NonStrict extends React.Component {
  componentDidMount() {
    console.log('mounting non strict');
  }

  componentDidUpdate() {
    console.log('updating');
  }
  //const [SSVisibility, setSSVisibility] = useState(true);
  render() {
    console.log('rendering Non strict');
    return (
      <div className="App">
        {/*   <SolarSystem isShowing={"yolo"} toggle={"polo"}></SolarSystem> */}
      </div>
    );
  }
}
const App = () => {
  return (
    <div>
      <React.StrictMode>
        <Strict />
      </React.StrictMode>
      <NonStrict />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

这篇关于react组件渲染方法无缘无故被调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆