主题中描述了我的问题
这里有效:
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
(在ofc类之外)func:
function mapDispatchToProps(dispatch) {
return {
...bindActionCreators({
toTakeData: loadItems,
dispatch: dispatch
}, dispatch)
};
}
最佳答案
来自react docs :
You have to be careful about the meaning of
this
in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bindthis.handleClick
and pass it toonClick
,this
will beundefined
when the function is actually called.This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without
()
after it, such asonClick={this.handleClick}
, you should bind that method.
如果你使用 babel,你可以使用 public class fields syntax这将导致 this
自动绑定(bind)。请注意,此方法仍然不在语言标准中,并且仅在 babel 将其转换为有效的 javascript 时才起作用:
searchHandler = event => { /* this is defined here ... */ }
es5 的方式是将函数绑定(bind)在构造函数
中:
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... */ }
}
请注意,箭头函数语法存在一些限制。例如,您不能在扩展它所定义的类的类中覆盖它。在 React 中,大多数时候这不是问题,因为 inheritance is discouraged赞成组合。
关于javascript - this.props 适用于一个函数,不适用于另一个 React-Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50836115/