是否可以从组件函数调用动作?

时间:2018-09-25 13:53:31

标签: reactjs react-redux

我有疑问是否可以从函数或事件处理程序中调用操作?我使用React-Redux。

示例:

    export class Page extends React.Component {

    onSomething() {
        this.props.onAdd();
      };

    render() {
        return (
             <div>
               <List
                 SomeMethod={this.onSomething};
               />
             </div>
           );
         }
    }

    Page.propTypes = {
      onAdd: PropTypes.func,
    };

    export function mapDispatchToProps(dispatch) {
      return {
        onAdd: evt => {
          dispatch(fetchAdd());
        },
      };
    }

const withConnect = connect(
  mapStateToProps,
  mapDispatchToProps,
);

const withReducer = injectReducer({ key: 'page', reducer });
const withSaga = injectSaga({ key: 'page', saga });

export default compose(
  withReducer,
  withSaga,
  withConnect,
)(Page);

我遇到错误,即:Uncaught TypeError: Cannot read property 'onAdd' of undefined

也许有人知道我在做什么不好?

1 个答案:

答案 0 :(得分:2)

您的this函数中只是缺少onSomething上下文。您可以通过类属性在构造函数中绑定它,也可以在jsx中将其绑定为箭头函数

export class Page extends React.Component {
  constructor() {
    this.onSomething = this.onSomething.bind(this);
  }
  // ...
};

或类属性(需要babel-plugin)

export class Page extends React.Component {
  onSomething = () => {
    this.props.onAdd();
  }
  // ...
};

或通过JSX中的箭头功能

render() {
  return (
    <div>
      <List
        SomeMethod={() => this.onSomething()};
      />
    </div>
  );
}