【问题标题】:Reactjs and this is undefinedReactjs,这是未定义的
【发布时间】:2015-11-29 07:45:04
【问题描述】:

我实际上正在尝试使用存储和操作开发一个简单的应用程序,并使用 Fluxible 响应组件,但我遇到了一个问题。

其实在我的组件方法add()中,“this”是未定义的……

我不知道是什么问题...

这是我的组件:

从“反应”导入反应;

class Client extends React.Component {

    constructor (props) {
      super(props);
    }

    add(e){
      this.context.dispatch('ADD_ITEM', {name:'Marvin'});
    }

    render() {
        return (
            <div>
                <h2>Client</h2>
                <p>List of all the clients</p>
                <button onClick={this.add}>Click Me</button>
                <ul>
                </ul>
            </div>
        );
    }


}

Client.contextTypes = {
    dispatch: React.PropTypes.func.isRequired
};

export default Client;

【问题讨论】:

    标签: javascript reactjs reactjs-flux fluxible


    【解决方案1】:

    试试这个按钮:

    <button onClick={this.add.bind(this)}>Click Me</button>
    

    【讨论】:

    • 我认为这不是一个好的。我需要我班上的那个,但它似乎不起作用
    【解决方案2】:

    来自docs

    方法遵循与常规 ES6 类相同的语义,这意味着它们不会自动将 this 绑定到实例。您必须明确使用 .bind(this) 或箭头函数 =>.

    所以要么绑定函数(我觉得这很乏味):

    <button onClick={this.add.bind(this)}>Click Me</button>
    

    或者您可以启用和利用Babel React ES6+ arrow functions feature

    add = (e) => {
        this.context.dispatch('ADD_ITEM', {name:'Marvin'});
    }
    

    【讨论】:

    • 做完之后,我有 this.context is undefined... :-/
    • 嗯,这取决于其他东西。也许你错过了类的一些函数调用? github.com/yahoo/fluxible#usage
    猜你喜欢
    • 2022-07-22
    • 1970-01-01
    • 2017-02-15
    • 2019-12-11
    • 2016-09-01
    • 2016-05-22
    • 2015-09-21
    • 1970-01-01
    • 2021-09-19
    相关资源
    最近更新 更多