[英]How prevent calling same api in different components in react js
I am working large reactjs application,In that application so many components are there and so many api services also there.我正在处理大型 reactjs 应用程序,在该应用程序中,有很多组件,还有很多 api 服务。 My problem is how to prevent calling same api in different components.
我的问题是如何防止在不同的组件中调用相同的 api。 Actually i want to call api one time then,i will use that api response entire application,so that we can prevent calling same api in different components.
实际上我想调用 api 一次,我将使用 api 响应整个应用程序,这样我们就可以防止在不同的组件中调用相同的 api。 So please give me any solution.
所以请给我任何解决方案。 check the below demo code:
检查以下演示代码:
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);`
You can actually call the API once your application is mounted.安装应用程序后,您实际上可以调用 API。 Usually this is done via
componentDidMount
or if you're using hooks, you can add it inside useEffect
.通常这是通过
componentDidMount
完成的,或者如果您使用钩子,您可以将它添加到useEffect
中。
And you can just pass down props.你可以传递道具。
A more better solution is to use redux
to your project, wherein the whole state of your application is inside a store in which you can connect using react-redux
.更好的解决方案是将
redux
用于您的项目,其中应用程序的整个 state 位于您可以使用react-redux
连接的商店内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.