this.props为一个func工作,不适用于另一个React-Redux

时间:2018-06-13 11:29:37

标签: 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(在类的c之外)func:

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

3 个答案:

答案 0 :(得分:1)

来自react docs

  

您必须小心JSX回调中this的含义。在   JavaScript,类方法默认不受约束。如果你忘记了   绑定this.handleClick并将其传递给onClickthis将为undefined   当实际调用该函数时。

     

这不是特定于React的行为;它是功能的一部分   在JavaScript中工作。通常,如果您引用的方法没有()   在它之后,例如onClick={this.handleClick},你应该绑定它   方法

如果您使用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... */ }
}

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

答案 1 :(得分:0)

对于无效的功能,请将其设为箭头功能

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

答案 2 :(得分:0)

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

问题是"这"。 "这" for searchHandler没有正确绑定。对于handleItemClick函数,因为它被定义为箭头函数和箭头函数get" this"从哪里定义。

相关问题