简体   繁体   中英

Accessing props in .then (React/redux)

My project is using react, redux, and redux-thunk.

I want to wait for my function to end before launching a function that clear my page. Unofortunately i have a problem accessing my function in .then

Here was my previous code without promise and then :

this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()

the problem was that sometime deleteTab() is called before sending the info to my server so not very good.

then i did :

Promise.resolve(this.props.dispatch(ScheduleAction(..)))
  .then(function(response) {
         this.props.deleteTab();
         console.log("TabDeleted !!!");
         return response
   })

The problem now is that i can't access this.props.deleteTab();

And i have this as error :

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined

If anyone have an idea on how to fix that by accessing props in .then, thanks in advance !!

Try this. You don't have access to this inside then. If you use arrow methods as below, you should be able to access it.

Promise.resolve(this.props.dispatch(ScheduleAction(..)))
  .then((response)=> {
         this.props.deleteTab();
         console.log("TabDeleted !!!");
         return response
   })

The problem you have here is that you lost the context of this keyword, which means this now is undefined.

Since you can access this.props outside the promise, what you want is to bind this inside your promise function by doing smth like this

Promise.resolve(this.props.dispatch(ScheduleAction(..)))
  .bind(this)
  .then(function(response) {
         this.props.deleteTab();
         console.log("TabDeleted !!!");
         return response
   })

hope this method work for you

const $this = this;
const { dispatch } = this.props;

Promise.resolve(dispatch(ScheduleAction(..)))
.then(function(response) {
  $this.deleteTab();
  console.log("TabDeleted !!!");
  return response;
})

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