首页 > 解决方案 > 当我想使用外部“this”关键字时出现“_this is undefined”错误

问题描述

在以下示例中,我收到此错误

类型错误:_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
}

简化调度.js


const dispatch = (type, text) => {
    return this.props.dispatch({
        type,
        text
    })
}

标签: javascriptreactjsimportbindingexport

解决方案


simplify_dispatch.js中,您正在尝试访问this.props,但这不是在正确的上下文中,因为您想this来自您的component_for_home_page. 我不确定你为什么不想只使用this.props.dispatch(...),但如果你坚持遵循这种方法,我建议将第三个参数传递给你的函数 in simplify_dispatch.jsthis.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)
}
...

推荐阅读