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

Reactjs 是否可以从组件函数调用操作?,reactjs,react-redux,Reactjs,React Redux,我有个问题,是否有可能从函数或事件处理程序调用操作?我使用React Redux 例如: 导出类页面扩展React.Component{ onSomething(){ this.props.onAdd(); }; render(){ 返回( ); } } Page.propTypes={ onAdd:PropTypes.func, }; 导出函数mapDispatchToProps(调度){ 返回{ onAdd:evt=>{ 分派(fetchAdd()); }, }; } const withC

我有个问题,是否有可能从函数或事件处理程序调用操作?我使用React Redux

例如:

导出类页面扩展React.Component{
onSomething(){
this.props.onAdd();
};
render(){
返回(
);
}
}
Page.propTypes={
onAdd:PropTypes.func,
};
导出函数mapDispatchToProps(调度){
返回{
onAdd:evt=>{
分派(fetchAdd());
},
};
}
const withConnect=connect(
MapStateTops,
mapDispatchToProps,
);
const withReducer=injectReducer({key:'page',reducer});
const withSaga=injectSaga({key:'page',saga});
导出默认组合(
带减速器,
维萨加,
通过连接,
)(第页);
我得到一个错误:
uncaughttypeerror:无法读取未定义的属性“onAdd”


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

你只是在你的
关于某件事的
功能中缺少
这个
上下文。您可以在构造函数中、通过类属性或作为jsx中的箭头函数绑定它

export class Page extends React.Component {
  constructor() {
    this.onSomething = this.onSomething.bind(this);
  }
  // ...
};
或类属性(需要babel插件)

或者通过JSX中的箭头函数

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

您从未连接过AFAICT组件。您只需随机导出
mapDispatchToProps
函数即可。@DaveNewton,好的,我将编辑代码。我正在连接。@PrEto您仍然没有连接
页面
组件。这是一个问题,每个新来者都会在这里面对并询问。但这在React官方文件中解释得很好,没有人读过。很奇怪。每天我都会在这里看到至少三个关于这个问题的问题。@Icepickel,非常感谢!
render() {
  return (
    <div>
      <List
        SomeMethod={() => this.onSomething()};
      />
    </div>
  );
}