Javascript this.props适用于一个函数,不适用于另一个函数
我的问题在主题中描述 它在这里工作:Javascript this.props适用于一个函数,不适用于另一个函数,javascript,reactjs,redux,react-redux,redux-thunk,Javascript,Reactjs,Redux,React Redux,Redux Thunk,我的问题在主题中描述 它在这里工作: handleItemClick = (e, { name }) => { if (name !== this.props.prevName) { document.getElementById(name).style = 'border: 3px solid black'; if (document.getElementById(this.props.prevName)) documen
handleItemClick = (e, { name }) => {
if (name !== this.props.prevName) {
document.getElementById(name).style = 'border: 3px solid black';
if (document.getElementById(this.props.prevName))
document.getElementById(this.props.prevName).style = 'border: 1px solid black';
this.props.dispatch({type: 'CHANGE_PREVNAME', payload: name});
let i = this.props.items.findIndex(element => {
return (element.general.firstName + ' ' + element.general.lastName) === name;
});
this.props.dispatch( { type: 'CHANGE_SELECTION', payload: this.props.items[i] } );
}
}
但在这里它不起作用:
searchHandler(event) {
this.props.dispatch( { type: 'CHANGE_TERM', payload: event.target.value } );
}
它是同一类的函数,这里mapDispatchToProps在C func类之外:
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({
toTakeData: loadItems,
dispatch: dispatch
}, dispatch)
};
}
对于不起作用的函数,将其设置为箭头函数 searchHandler=事件=>{…} 问题在于这一点。searchHandler的此未正确绑定。对于handleItemClick函数,它被定义为箭头函数,箭头函数从定义它的地方获取 来自: 在JSX回调中,您必须小心这一点的含义。在里面 默认情况下,类方法不受绑定。如果你忘了 绑定this.handleClick并将其传递给onClick,这将是未定义的 当函数实际被调用时 这不是特定的行为;这是如何发挥作用的一部分 在JavaScript中工作。通常,如果您引用的方法没有 在它之后,比如onClick={this.handleClick},您应该绑定它 方法 如果您使用babel,您可以使用,这将导致自动绑定。请注意,此方法仍不在语言标准中,并且仅在巴贝尔将其转换为有效javascript时才起作用:
searchHandler = event => { /* this is defined here ... */ }
es5方法是在构造函数中绑定函数:
请注意,arrow函数语法有一些限制。例如,您不能在扩展它所定义的类的类中重写它。在react中,这在大多数情况下都不是问题,因为有利于合成。请添加searchHandler构造函数并连接脚本对于它不工作的函数,将其设置为arrow函数。searchHandler=event=>{…}这将适用于you@AbhayShiro天哪,我太笨了,谢谢你!我们都从错误中吸取教训,这就是所谓的。请注意,这只起作用,因为巴贝尔将其转换为有效的javascript。尽管将来可能会出现,但它仍然没有正式列入语言标准。es5的另一种方法是在构造函数中将函数绑定到它。
searchHandler = event => { /* this is defined here ... */ }
class MyComponent extends Component {
constructor(props) {
super(props);
// bind this to your handler
this.searchHandler = this.searchHandler.bind(this);
/* other initialization */
}
searchHander(event) { /* you can access this here... */ }
}