【问题标题】:ES6 Function binding gets undefined (this.state captures the values)ES6 函数绑定未定义(this.state 捕获值)
【发布时间】:2019-07-03 02:52:22
【问题描述】:

我试图在单击按钮时调用一个函数(具有标题和类别的值)。这些值存储在组件的状态中,并且当我 console.log(this.state) 时这些值是正确的。但是,当调用该函数时,title 的值仍然存在,但 category 变得未定义。

当我将要调用的函数放入另一个函数时它可以工作,我不确定为什么原始绑定导致其中一个值变得未定义。 “这个”丢失了,丢失在哪里?

我尝试理解React this.state is undefined?https://javascript.info/bindBinding this? Getting undefined?Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 中的解释,但我认为它不能解释我的行为。

我是否使用了太多导致问题的 this/bind?

class CreateItem extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            inputTitle: '',
            selectedCategory: ''
        }
    }

    // works when I put the createItem(title, category) inside this function
    onClickAddItem() {
        this.props.createItem(this.state.inputTitle, this.state.selectedCategory);
    }

    render() {
        <div>
        // this doesn't work (edit: due to typo where it should be selectedCategory and not inputCategory) 
        <Button text={'Create'} onClick={this.props.createItem.bind(this, this.state.inputTitle, this.state.inputCategory)}/>

        // this works
        <Button text={'Create'} onClick={this.onClickAddItem.bind(this)}/>
        </div>
    }
}

// createPublicChat function is in another file

export function createItem(title, category) {
    console.log(title, category);
}

我希望 title = "BookA", category = "Fiction" 的输出将“Book A Fiction”打印到控制台,但实际输出是“Book A undefined”

编辑:有一个错字导致了未定义的问题(正如@bkm412 所指出的那样)。现在都可以了,谢谢!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我觉得有错别字

    <Button text={'Create'} onClick={this.props.createItem.bind(this, this.state.inputTitle, this.state.inputCategory)}/>
    

    this.state.inputCategory 应改为this.state.selectedCategory

    【讨论】:

    【解决方案2】:

    我注意到这段代码中有一些不好的做法。 使用一些参数调用函数的更好方法如下:

    <Button onClick={() => this.props.createItem(this.state.title, this.state.selectedcategory)} />
    

    另外,为了防止绑定错误,应该将所有函数绑定在一个地方,即在构造函数内部。

    constructor(props) {
            super(props);
            this.state = {
                inputTitle: '',
                selectedCategory: ''
            }
            this.createItem = this.createItem.bind(this);
        }
    

    另外你不需要绑定作为props传递给组件的函数。

    【讨论】:

      【解决方案3】:

      首先不要在render 方法中绑定函数,因为每当重新渲染组件时,它都会进行新的绑定。如果你想绑定一个函数,完美的地方是在constructor 方法中。

      您也可以使用箭头函数来避免绑定问题。
      例如:onClickAddItem=()=&gt;{}

      这样做您不必将类函数显式绑定到this,因为箭头函数没有与之关联的this,而是指向封闭的词法范围。

      在此处阅读有关箭头功能的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2020-01-25
        相关资源
        最近更新 更多