What is the purpose of having functions like componentWillMount in React.js?

前端 未结 5 865
一个人的身影
一个人的身影 2021-02-04 00:32

I have been writing components in React.js recently. I have never had to use methods like componentWillMount and componentDidMount.

rend

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 01:33

    componentDidMount only runs once and on the client side. This is important, especially if you're writing an isomorphic app (runs on both the client and server). You can use componentDidMount to perform tasks require you to have access to window or the DOM.

    From Facebook's React Page

    If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval, or send AJAX requests, perform those operations in this method.
    

    componentWillMount has fewer use cases (I don't really use it), but it differs in that it runs both on the client and server side. You probably don't want to put event listeners or DOM manipulations here, since it will try to run on the server for no reason.

提交回复
热议问题