javascript – 使用react调用api的正确方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用react调用api的正确方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2222字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 使用react调用api的正确方法](/upload/InfoBanner/zyjiaocheng/735/1a0a04d7127b4cbba3abf01440435bd8.jpg)
我有一个如下的反应代码,它基本上创建了一个树形图:
class ChartModal extends Component{
constructor(props){
super(props)
}
callApi(){
fetch(someurl)
.then((result) => {
return result.json();
}).then((jsonResult) => {
console.log(jsonResult);
})
}
render(){
return(
<Modal
onOk={() => this.props.toggleVisibility()}
onCancel={() => this.props.toggleVisibility()}
visible={this.props.isVisible}
okText={'ok'}
cancelText={'cancel'}
confirmLoading={false}
title="Intent distribution chart"
>
<h1>HOWDY</h1>
<TreeMap
data = {this.callApi()}//this is where i want the data returned by apicall
width={400}
valueUnit={'count'}
/>
</Modal>
)
}
}
现在我希望api调用返回的数据在树图组??件中使用,但我现在这样做的方式似乎不起作用.
当我运行它时,树映射中的数据变为null,尽管我希望api调用返回的json存在.
解决方法:
您需要在componentWillMount或任何其他生命周期钩子中调用API,并在API回调中使用setState来确保将结果设置为组件状态变量.这样,在setState之后,您的组件可以访问API调用解析的值.
注意:this.state.result在第一次渲染期间将为null.在访问this.props.data之前,请确保在TreeMap组件中进行空检查.
IMP NOTE
@ aram90关于未安装组件上的setState调用的一个很好的建议.为了避免这个this.canSetState,实例变量由我定义并添加以防止对未安装的组件进行任何可能的setState调用.
我使用这种方法只是为了尽可能早地调用API,即使它意味着纳秒.但是,另一种方法是在componentDidMount中调用API,然后相应地检查this._ismounted实例变量.有关此结帐的更多信息,请参阅此处的答案Is there a way to check if the react component is unmounted?. React docs建议不要使用isMounted().
有很多方法可以实现这一点,但这更像是React的方式.
class ChartModal extends Component{
constructor(props){
super(props)
this.state = {
result: null
}
this.canSetState = false;
}
componentWillMount() {
this.canSetState = true;
this.callApi();
}
componentWillUnmount() {
this.canSetState = false;
}
callApi(){
fetch(someurl)
.then((result) => {
return result.json();
}).then((jsonResult) => {
this.canSetState && this.setState({result: jsonResult})
})
}
render(){
return (
<Modal
onOk={() => this.props.toggleVisibility()}
onCancel={() => this.props.toggleVisibility()}
visible={this.props.isVisible}
okText={'ok'}
cancelText={'cancel'}
confirmLoading={false}
title="Intent distribution chart"
>
<h1>HOWDY</h1>
<TreeMap
data={this.state.result}
width={400}
valueUnit={'count'}
/>
</Modal>
)
}
}
内容总结
以上是互联网集市为您收集整理的javascript – 使用react调用api的正确方法全部内容,希望文章能够帮你解决javascript – 使用react调用api的正确方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。