简体   繁体   中英

React - Display loading screen while ajaxing

Unlike some of the other questions, my component has already fully loaded. I have managed to create the loading screen BEFORE the component was loaded, but now I'm unsure of how to create it after.

What I'm trying to do right now is make an ajax call which then changes the state/(redux store) which should then display my loading screen.

eg a child component calls an ajax:

let url = "src/php/search.php";
axios.get(url, {
params: {
  report_id: data.id,
  type: "get_report"
}
})
.then( r =>
  {
    console.log(r.data);
    this.props.dispatch( { type: "set_loading", payload: false } );
    this.props.dispatch({ type: "set_report", payload: r.data });
    this.props.router.push('/form/start');
  }
);

This is the parent render:

render()
{
  return (
    <div style={{padding: "0 5px"}}>
      <LoadingScreen loading={this.props.loading} /> <<<<< The loading screen
      <div style={{padding: "0"}}>
        <Link activeClassName="active" className="default bottom-radius" to='main'>Main Menu</Link>
        <Link activeClassName="active" className="default bottom-radius" to='search'>Search</Link>
        <a className="bottom-radius" style={{ float: "right", color : "blue", backgroundColor: "red", padding: "5px", cursor : "pointer" }} onClick={this.logout}>Logout</a>
      </div>
      <div style={{paddingTop: "10px"}}>
        {this.props.children}
      </div>

    </div>
  );
}

const App = connect(
(store) =>
{
    return {
      "user_id": store.component.user_id,
      loading: store.component.loading
    };
}) (AppComponent);

I was expecting the this.props.loading to turn true, which then displays the loading screen, which then goes away on the then in the child component. But instead nothing happens. Will I need a middleware for this instead?

You need to dispatch an action to set the state to loading when you send an ajax request . Instead you are dispatching an action in the success call of ajax, soon after which you send the set_report action which overrides the set_loading action even before you notice.

Use the ajax call like

axios.get(url, {
params: {
  report_id: data.id,
  type: "get_report"
}
})
.then( r =>
  {
    console.log(r.data);
    this.props.dispatch({ type: "set_report", payload: r.data });
    this.props.router.push('/form/start');
  }
);

and call this dipatch where you send an ajax call

    this.props.dispatch( { type: "set_loading", payload: false } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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