最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call API on React app start - Stack Overflow

programmeradmin2浏览0评论

I am working in a React app, at the start of the application I need to make a GET request to a external API that give me some settings, this call I need to make it also when the user login and logout of the system. Currently I have that implemented, now I am not sure where should I call it.

I have a ponent, and inside I have the method ComponentWillReceiveProps there I am calling the request, however it's calling many many times and this is not what I want. So, which method os the proper to call it? depending of the answer of the API some of the ponents will be rendered or not. Thank you

I am working in a React app, at the start of the application I need to make a GET request to a external API that give me some settings, this call I need to make it also when the user login and logout of the system. Currently I have that implemented, now I am not sure where should I call it.

I have a ponent, and inside I have the method ComponentWillReceiveProps there I am calling the request, however it's calling many many times and this is not what I want. So, which method os the proper to call it? depending of the answer of the API some of the ponents will be rendered or not. Thank you

Share Improve this question asked Aug 29, 2017 at 22:14 Sredny M CasanovaSredny M Casanova 5,06127 gold badges78 silver badges119 bronze badges 1
  • any time props change, ComponentWillReceiveProps is called so thats what causing the multiple calls to the api, one of the mount methods would work. this a a good article. busypeoples.github.io/post/react-ponent-lifecycle – TimCodes Commented Aug 29, 2017 at 22:18
Add a ment  | 

2 Answers 2

Reset to default 7

I would call the external API in ponentDidMount, since it's the remended place to perform side effects (source).

Once you get the data, you can store it in the ponent state (or redux, if you have that). And then decide what to render in the render method based on the state.

Example:

class App extends React.Component {
  ponentDidMount() {
    callExternalApi().then(data => {
      this.setState({
        data: data,
      });
    });
  }

  render() {
    const { data } = this.state;

    if (data === 'render div') {
      return <div />;
    }
    return <span />;
  }
}

Something like this for example:

const mapDispatchToProps = dispatch => ({
  onLoad: (payload ) => {
    dispatch({ type: APP_LOAD, payload});}  
});

class App extends React.Component {
 ponentWillMount() {
   this.props.onLoad(Promise.all([reduxagent.get.all()]));
 }
}

Here you may load your props within promise right after application starts.

发布评论

评论列表(0)

  1. 暂无评论