在下面的示例中我收到此错误
TypeError: _this is undefined
我尝试了很多方法,但找不到解决该错误的方法,我该如何解决?
component_for_home_page.js
import { dispatch } from 'dispatch'
class Home extends PureComponent {
componentDidMount() {
dispatch('ADD_TEXT', 'Beep, Boop')
// instead of following
// this.props.dispatch({
// type: 'ADD_TEXT'
// text: 'Beep, Boop'
// })
//
}
render() {
return (<p>{this.props.text}</p>)
}
}
function mapStateToProps(state) {
return {
...state
}
}
const connectedHomeComponent = connect(mapStateToProps)(Home)
export {
connectedHomeComponent
}
simplify_dispatch.js
const dispatch = (type, text) => {
return this.props.dispatch({
type,
text
})
}
最佳答案
在 simplify_dispatch.js
中,您尝试访问 this.props
但它不在正确的上下文中,因为您想要 this
> 来自您的 component_for_home_page
。我不知道为什么你不想只使用 this.props.dispatch(...) ,但如果你坚持遵循这种方法,我建议将第三个参数传递给你的函数在 simplify_dispatch.js
中,this.props
或 this.props.dispatch
simplify_dispatch.js
const dispatch = (type, text, passedDispatch) => {
return passedDispatch({
type,
text
})
}
component_for_home_page.js
...
componentDidMount() {
dispatch('ADD_TEXT', 'Beep, Boop', this.props.dispatch)
}
...
关于javascript - 当我想使用外部 "_this is undefined"关键字时出现 "this"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60609953/