2017-08-29 49 views
2

我在React应用程序中工作,在应用程序的开始处我需要向外部API发出GET请求,该应用程序给了我一些设置,这个调用我需要在用户登录和注销系统。目前我已经实施了,现在我不知道应该在哪里调用它。在React应用程序启动时调用API

我有一个组件,里面我有方法ComponentWillReceiveProps那里我打电话的请求,但它调用很多次,这不是我想要的。那么,哪种方法适合称之为?取决于API的答案,一些组件将被渲染或不渲染。谢谢

+0

随时更改道具,ComponentWillReceiveProps被称为因此多数民众赞成什么造成对API的多个呼叫,的安装方法之一是可行的。这是一篇很好的文章。 http://busypeoples.github.io/post/react-component-lifecycle/ – TimCodes

回答

1

事情是这样的,例如:

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

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

在这里,您可以后立即启动应用程序的承诺中加载您的道具。

+0

很高兴帮助你:) – Vyacheslav

4

我会在componentDidMount中调用外部API,因为它是推荐执行副作用的地方(source)。

一旦获得数据,就可以将其存储在组件状态(或者如果有的话)。然后根据状态决定在render方法中呈现的内容。

例子:

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

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

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