调用API时componentWillMount与componentDidMount

时间:2019-08-29 10:07:58

标签: reactjs

我刚刚在我的React App中添加了Facebook Login(Javascript SDK)。问题是,当我在componentDidMount中添加Facebook API时,该网页的加载速度非常慢。因此,即使出现了弃用警告,我也尝试了另一种方法,即componentWillMount。但是,将API调用更改为componentWillMount似乎大大提高了加载速度。

在网站性能方面,您认为componentWillMount和componentDidMount有区别吗?并且可以使用componentWillMount方法吗?还是您强烈建议componentDidMount?

class FacebookAuth extends Component {
  UNSAFE_componentWillMount() {
    window.fbAsyncInit = () => {
      window.FB.init({
        appId: "ID",
        cookie: true, 
        xfbml: true, 
        version: "v4.0" 
      });
}}

2 个答案:

答案 0 :(得分:0)

您不应使用componentWillMount,它将被React v17完全删除。

在您的用例中,应该没有明显的性能差异。这一定是另一个问题。您的API调用应全部位于componentDidMount中。

答案 1 :(得分:0)

随着React的新更新,componentWillMount可能在加载组件时调用多次,因此将表现出不可预知的行为。这就是为什么不建议使用componentWillMount的原因。如果您仍然认为将代码放入componentWillMount中会减慢页面加载速度,请尝试按以下步骤将其移至componentDidUpdate

componentDidUpdate(prevProps){
  if(prevProps !== this.props){
      //your code here
  }
}