admin管理员组文章数量:1355532
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
- 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
2 Answers
Reset to default 7I 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.
本文标签: javascriptCall API on React app startStack Overflow
版权声明:本文标题:javascript - Call API on React app start - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743992962a2572484.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论