gpt4 book ai didi

javascript - 当我想使用外部 "_this is undefined"关键字时出现 "this"错误

转载 作者:行者123 更新时间:2023-12-02 21:31:38 26 4
gpt4 key购买 nike

在下面的示例中我收到此错误

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.propsthis.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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com