首页 > 解决方案 > 是否可以从组件功能中调用操作?

问题描述

我有疑问是否有可能从函数或事件处理程序调用操作?我使用 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

也许有人知道我做错了什么?

标签: reactjsreact-redux

解决方案


您只是缺少函数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>
  );
}

推荐阅读