Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在Redux中,何时需要使用.bind(this)_Reactjs_Redux - Fatal编程技术网

Reactjs 在Redux中,何时需要使用.bind(this)

Reactjs 在Redux中,何时需要使用.bind(this),reactjs,redux,Reactjs,Redux,有时我真的很困惑,什么时候我需要将.bind(this)附加到方法(ES5)或使用arrow函数(ES6) e、 g 我说得对吗?谢谢是的,每次将自定义函数传递给事件处理程序(如onChange或onSubmit)时,都需要.bind 这是由React.createClass()与extends React.Component中的This上下文差异造成的 使用React.createClass()将自动正确绑定此上下文(值),但使用ES6类时并非如此。使用ES6方式(通过扩展React.Comp

有时我真的很困惑,什么时候我需要将
.bind(this)
附加到方法(ES5)或使用arrow函数(ES6) e、 g


我说得对吗?谢谢

是的,每次将自定义函数传递给事件处理程序(如
onChange
onSubmit
)时,都需要
.bind

这是由React.createClass()与extends React.Component中的
This
上下文差异造成的

使用React.createClass()将自动正确绑定此上下文(值),但使用ES6类时并非如此。使用ES6方式(通过扩展React.Component)时,此上下文默认为
null
。类的属性不会自动绑定到React类(组件)实例

顺便说一句,bind不是唯一可用的选项。有关我所知道的所有方法的摘要,请参阅


PS:实际上,这不是Redux特有的东西——与Redux的工作方式无关。这是一个纯粹的与ReactJS相关的行为。

在您的示例中,您可以选择箭头函数,并按照所述创建表单

另一个选项是使用一个构造函数进行绑定

constructor() {
  super();
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}
那么你的表格是

是的,你是对的,当然,如果你的意思是
这是你的课程背景。在我看来,在这些情况下使用
.bind
更清晰,但我不知道这是否更有效。

有多种方法可以将函数绑定到正确的上下文

当您想要使用函数或属性时,您是对的 在React类的上下文中定义的,那么您需要 绑定你的函数

绑定函数的另一种方法是在构造函数中指定绑定

类应用程序扩展了React.Component{
构造函数(){
超级();
此.state={
瓦尔:“abc”
}
}
handleSubmit(e){
console.log(this.state.val)
}
手变(e){
console.log(this.state.val)
}
render(){
返回(
this.handleChange(e)}onSubmit={e=>this.handleSubmit(e)}>
)
}
}
ReactDOM.render(,document.getElementById('app'))


感谢信可能重复。我更喜欢arrow函数,因为它是ES6,而.bind()是ES5。这将在每次渲染时创建新函数。不建议这样做(例如,此函数的“引用”在每个渲染上都不同,因此很难知道componentShouldUpdate)@pie6k,是的,你是对的,但是这是一个快速解决方案。查看有关如何避免渲染中绑定的详细答案
<form onChange={this.handleChange} onSubmit={this.handleSubmit}>
constructor() {
  super();
  this.handleChange = this.handleChange.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}
constructor(){
  super();
  this.handleSubmit = this.handleSubmit.bind(this);
  this.handleChange = this.handlechange.bind(this);

}