在以下示例中,我收到此错误
TypeError:_this未定义
我尝试了许多方法,但找不到解决错误的方法,我该如何解决?
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
}
simple_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)
}
...