【问题标题】:How prevent calling same api in different components in react jsreactjs中如何防止在不同组件中调用相同的api
【发布时间】:2020-03-16 02:38:14
【问题描述】:

我正在处理大型 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);`

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    一旦您的应用程序被挂载,您就可以实际调用 API。通常这是通过componentDidMount 完成的,或者如果您使用钩子,您可以将其添加到useEffect 中。

    你可以只传递道具。

    更好的解决方案是在您的项目中使用redux,其中您的应用程序的整个状态都在您可以使用react-redux 连接的商店中。

    【讨论】:

    • 嗨 Rem,我已经在我的项目中使用 react-redux,并且也在使用 store,但这里我遇到的问题是:让我们解释一下,第一个组件 api 服务正在调用该服务响应也存储在商店中,我通过使用 mapStateToProps 函数使用该商店数据,这对我来说完全没问题,但是当我第一次重定向到第二个组件时,先前的 redux 商店返回 api 响应,但是当第二次刷新页面时,它变得空了。
    • 我可以看一下你的代码,以便我可以正确查看它吗?
    • @AshokSudagani but when refresh the page second time it is getting null. 是什么意思?如果您刷新浏览器选项卡,则意味着您的 js 代码再次初始化,并且您存储在内存中的数据已被清除。
    • 大家好,请查看上面的演示代码,可能是我犯了任何错误
    • @AshokSudagani 您如何安装这两个组件?如果在显示 SecondComponent 之前卸载 FirstComponent,然后刷新选项卡,肯定会清理内存。我认为您需要的是一个可以包装这两个组件的容器。卸载两者中的任何一个都没有关系,只要保持容器已安装即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 2018-05-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多