Reactjs 渲染两次

3
在我的ReactJS项目中,组件被渲染了两次。如果我移除componentDidMount,问题就解决了。但我需要它在我的项目中。我尝试了网上的解决方案,但是没有成功。
App.js
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    fetch("https://reqres.in/api/users?page=2")
      .then(res => res.json())
      .then(result => {
        this.setState({
          users: result.data
        });
      });
  }

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route exact path="/" render={() => <Home />} />
        </Switch>
      </BrowserRouter>
    );
  }
}

Home.js

export default class Home extends Component {
  render() {
    console.log("Render");
    return (
      <div>
        <h1>console.log render twice</h1>
      </div>
    );
  }
}

在 Home.js 中,console.log 会输出两次。

https://codesandbox.io/s/wyjk931z6l


4
它将呈现两次,那有什么问题?这就是API调用的工作方式。 - Just code
2
请解释一下为什么您认为多次渲染组件是不好的。因为这就是React(或任何其他使用屏幕的软件)的工作方式。 - user5734311
1个回答

3

当你在componentDidMount钩子中发起API调用并且请求成功后执行了setState时,你的App组件会重新渲染。由于这个原因,即使子组件的props没有改变,它们也会重新渲染。为了避免这种情况,你可以通过继承React.PureComponent来编写子组件,它将通过对比props和state的浅层次比较来实现shouldComponentUpdate方法。

export default class Home extends PureComponent {
  render() {
    console.log("Render");
    return (
      <div>
        <h1>console.log render twice</h1>
      </div>
    );
  }
}

演示链接


1
好的回答,但我们不应该先弄清楚OP为什么认为非问题是问题吗?我担心告诉他们关于shouldComponentUpdate可能会鼓励一种本来就应该避免的不良实践。 - user5734311
@ChrisG 是的,你说得对。然而,我试图解释了 OP 代码中到底在发生什么,并建议使用 PureComponent 而不是自己实现 shouldComponentUpdate。 - Shubham Khatri

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接