在 .then (React/redux) 中访问道具
Accessing props in .then (React/redux)
我的项目正在使用 react、redux 和 redux-thunk。
我想等待我的功能结束,然后再启动清除我的页面的功能。不幸的是,我在 .then
中访问我的函数时遇到问题
这是我之前没有承诺的代码然后:
this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()
问题是有时会在将信息发送到我的服务器之前调用 deleteTab(),所以不太好。
然后我做了:
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
现在的问题是我无法访问this.props.deleteTab();
我有这个错误:
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
如果有人知道如何通过访问 .then 中的道具来解决这个问题,请提前致谢!!
这里的问题是您丢失了 this
关键字的上下文,这意味着 this
现在是未定义的。
因为你可以在 promise 之外访问 this.props
,你想要的是 bind
this
在你的 promise
函数中通过这样做
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.bind(this)
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
试试这个。那时您无权访问此内容。如果您使用如下箭头方法,您应该可以访问它。
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then((response)=> {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
希望这个方法对你有用
const $this = this;
const { dispatch } = this.props;
Promise.resolve(dispatch(ScheduleAction(..)))
.then(function(response) {
$this.deleteTab();
console.log("TabDeleted !!!");
return response;
})
我的项目正在使用 react、redux 和 redux-thunk。
我想等待我的功能结束,然后再启动清除我的页面的功能。不幸的是,我在 .then
中访问我的函数时遇到问题这是我之前没有承诺的代码然后:
this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()
问题是有时会在将信息发送到我的服务器之前调用 deleteTab(),所以不太好。
然后我做了:
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
现在的问题是我无法访问this.props.deleteTab();
我有这个错误:
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
如果有人知道如何通过访问 .then 中的道具来解决这个问题,请提前致谢!!
这里的问题是您丢失了 this
关键字的上下文,这意味着 this
现在是未定义的。
因为你可以在 promise 之外访问 this.props
,你想要的是 bind
this
在你的 promise
函数中通过这样做
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.bind(this)
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
试试这个。那时您无权访问此内容。如果您使用如下箭头方法,您应该可以访问它。
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then((response)=> {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
希望这个方法对你有用
const $this = this;
const { dispatch } = this.props;
Promise.resolve(dispatch(ScheduleAction(..)))
.then(function(response) {
$this.deleteTab();
console.log("TabDeleted !!!");
return response;
})