【问题标题】:"_this is undefined" error when i want to use external "this" keyword当我想使用外部“this”关键字时出现“_this is undefined”错误
【发布时间】:2020-06-21 21:32:48
【问题描述】:

在下面的例子中我收到了这个错误

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
    })
}

【问题讨论】:

    标签: javascript reactjs import binding export


    【解决方案1】:

    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)
    }
    ...
    

    【讨论】:

    • 这正是我想学的,非常感谢。
    猜你喜欢
    • 2021-08-21
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 2020-10-31
    • 2013-01-21
    相关资源
    最近更新 更多