繁体   English   中英

如何防止在反应js的不同组件中调用相同的api

[英]How prevent calling same api in different components in react js

我正在处理大型 reactjs 应用程序,在该应用程序中,有很多组件,还有很多 api 服务。 我的问题是如何防止在不同的组件中调用相同的 api。 实际上我想调用 api 一次,我将使用 api 响应整个应用程序,这样我们就可以防止在不同的组件中调用相同的 api。 所以请给我任何解决方案。 检查以下演示代码:

enter code here

`FirstComponent:
 ——————————————
 Class FirstComponent extends Component {
 constructor(props){
 this.setState={}
}
componentDidMount() {
this.props.dispatch(getById(1)); //here first time I am calling api
}
render(){
return(
———HTML Code HERE———
)
}
const mapStateToProps = state => {
  return {
    registrationData: state.RegistrationDemand.registrationData 
    // here I am getting response through redux reducer store
    };
};
export default compose(
  translate,
  withRouter,
  connect(mapStateToProps)
)(FirstComponent);

SecondComponent:
——————————————
Class SecondComponent extends Component {
constructor(props){
this.setState={}
}
componentDidMount() {
this.props.dispatch(getById(1));   //here I need to prevent this second time api calling
}
render(){
return(
———HTML Code HERE———
)
}
const mapStateToProps = state => {
  return {
    registrationData: state.RegistrationDemand.registrationData 
//without calling second component,If I use this one first time when I redirect to this page data is coming hereabout when I refresh second time it is getting null.
    };
};
export default compose(
  translate,
  withRouter,
  connect(mapStateToProps)
)(SecondComponent);`

安装应用程序后,您实际上可以调用 API。 通常这是通过componentDidMount完成的,或者如果您使用钩子,您可以将它添加到useEffect中。

你可以传递道具。

更好的解决方案是将redux用于您的项目,其中应用程序的整个 state 位于您可以使用react-redux连接的商店内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM