【问题标题】:react component render method being called twice for no reasonreact组件渲染方法被无缘无故调用了两次
【发布时间】:2020-03-28 17:32:38
【问题描述】:
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; 

通过这个简单的代码,我的渲染方法被调用了两次。我不明白为什么

【问题讨论】:

标签: reactjs html-rendering


【解决方案1】:

这是因为严格模式,下面的代码没有演示它,因为 SO 将在生产集为 true 的情况下构建它(我认为)。

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>

【讨论】:

  • '虽然它对我来说可能永远是晦涩难懂的,但我不得不意识到它的力量' - Nathen Algren 船长我的意思是好吧,因为它是严格模式,但为什么
  • @noob7 React 需要多次渲染到detect possible problems。为生产构建时,严格模式不会这样做(这就是 sn-p 不播种多个日志的原因)
猜你喜欢
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2015-02-21
  • 2012-11-19
  • 2022-07-22
  • 2019-05-26
  • 2020-07-05
  • 2017-07-23
相关资源
最近更新 更多