react component render method being called twice for no reason

…衆ロ難τιáo~ 提交于 2020-04-14 16:50:00

问题


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; 

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


回答1:


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>


来源:https://stackoverflow.com/questions/60899323/react-component-render-method-being-called-twice-for-no-reason

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!