【发布时间】:2019-07-03 02:52:22
【问题描述】:
我试图在单击按钮时调用一个函数(具有标题和类别的值)。这些值存储在组件的状态中,并且当我 console.log(this.state) 时这些值是正确的。但是,当调用该函数时,title 的值仍然存在,但 category 变得未定义。
当我将要调用的函数放入另一个函数时它可以工作,我不确定为什么原始绑定导致其中一个值变得未定义。 “这个”丢失了,丢失在哪里?
我尝试理解React this.state is undefined?、https://javascript.info/bind、Binding 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