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

标签 javascript reactjs import binding export

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

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/

相关文章:

javascript - Bootstrap 网格对齐与 Angular JS

javascript - 以 Angular 使用 sessionStorage 的最佳方式

javascript - 如何为 Pug、React 和 ES6 设置 webpack

python - 如何在 Python 中将参数传递给导入的脚本

python - 无法在 PyCharm 中加载 DLL python 模块。在 IPython 中运行良好

javascript - 在继续 AJAX post 之前检查验证

javascript - 单元测试 Typescript 装饰器

reactjs - 使用动态 URL 参数调用 React 组件

javascript - 传单 JS : Cannot read property 'addLayer' of undefined while rendering drawnItems on Map

SQL 2005 从文件中获取数据