javascript - this.props 适用于一个函数,不适用于另一个 React-Redux

标签 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))
            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 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 自动绑定(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/

相关文章:

django - 在 django-react-redux 中 PUT 文件请求

JavaScript - 选择单选按钮后删除以前的字段集

javascript - 在 Google Apps 脚本 (JavaScript) 中获取特定字符串格式的第二天日期

javascript - 在 Node.js 中递归创建嵌套数组

javascript - 如何将 html 转换为 draftjs?

webpack - 引用错误 : global is not defined at eval

reactjs - 在 Side Effect 中使用全局化的 Redux 选择器创建循环依赖

javascript - 使用 react-router-redux 访问参数

javascript - 无法正确更新状态中的总值

javascript - 如何从 Admin-on-rest 框架更改过滤器的 key ?