[英]this.props 'missing' method using conect from react-redux
[英]this.props working for one func and don't work for another React-Redux
我的问题在主题中进行了描述
在这里工作:
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
(在mapDispatchToProps
类之外)func:
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({
toTakeData: loadItems,
dispatch: dispatch
}, dispatch)
};
}
从react docs :
你必须小心的意思
this
在JSX回调。 在JavaScript中,默认情况下不绑定类方法。 如果你忘了绑定this.handleClick
并把它传递到onClick
,this
将是undefined
,当函数实际上是调用。这不是特定于React的行为; 它是函数在JavaScript中工作方式的一部分。 通常,如果引用的方法后面没有
()
,例如onClick={this.handleClick}
,则应绑定该方法。
如果您使用的巴贝尔则可以使用公用类领域的语法 ,这将导致this
被automatially约束。 请注意,此方法仍不在语言标准中,并且只能工作,因为babel将其转换为有效的javascript:
searchHandler = event => { /* this is defined here ... */ }
es5的方式是将函数绑定到constructor
函数中:
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... */ }
}
请注意,箭头函数语法有一些限制。 例如,您不能在扩展定义它的类的类中重写它。在大多数情况下,这都不是问题,因为不鼓励使用继承来支持合成。
对于该功能不起作用,请使其成为箭头功能
searchHandler = (event) => { ... }
searchHandler(event) {
this.props.dispatch( { type: 'CHANGE_TERM', payload: event.target.value } );
}
问题是“这个”。 searchHandler的“ this”未正确绑定。 对于handleItemClick函数,因为它定义为箭头函数,而箭头函数从定义的位置获取“ this”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.