this.props 为一个功能工作,不为另一个 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 } );
}

它的功能和class一样,这里mapDispatchToProps(在class ofc之外)func:

 function mapDispatchToProps(dispatch) {
    return {
      ...bindActionCreators({
        toTakeData: loadItems,
        dispatch: dispatch
      }, dispatch)
    };
}

对于不起作用的函数,将其设为箭头函数

searchHandler = (event) => { ... }

searchHandler(event) {
    this.props.dispatch( { type: 'CHANGE_TERM', payload: event.target.value } );
}

问题出在 "this"。 "this" 未正确绑定 searchHandler。对于 handleItemClick 函数,因为它被定义为箭头函数,箭头函数从它定义的地方获取 "this"。

来自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 bind this.handleClick and pass it to onClick, this will be undefined 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 as onClick={this.handleClick}, you should bind that method.

如果你使用 babel,你可以使用 public class fields syntax 这将导致 this 被自动绑定。请注意,此方法仍然不在语言标准中并且仅在 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... */ }
}

请注意,箭头函数语法有一些限制。例如,您不能在 class 扩展它定义的 class 的 es 中覆盖它。在 React 中,大多数时候这不是问题,因为 inheritance is discouraged 支持组合。