将分派函数作为回调传递给另一个实例属性以稍后执行



抱歉伪代码。我认为这个问题可以这样理解。在一个可重复的例子中工作

考虑以下伪代码:

类foo:

let fooInstance = null
class Foo() {
constructor(){
fooInstance = this;
this.fooCallback = null // property to assign callback
}
static getInstance() {
return fooInstance
}
callbackExecutor() {
if (this.fooCallback)  // callback always null here even the assignment is ok in the component
this.fooCallback();
}
}

React-redux组件:

import { argumentFunc } from 'src/argumentFunc'
class MyComponent extends Component {
constructor(props) { 
...
}
componentDidUpdate(prevProps, prevState) {
const foo = Foo.getInstance()
if (whateverCond) {
// callback assignment to instance. this.props.argumentFunc() works if called here
foo.fooCallback = this.props.argumentFunc(); 
}
}
}

...
const mapDispatchToProps = (dispatch) => ({
argumentFunc: () => dispatch(argumentFunc()),
})
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)

我将回调分配给实例,但随后在callbackExecutor中,this.fooCallback为空。

我试着:
foo = this.props.argumentFunc();
foo = this.props.argumentFunc;
foo = () => this.props.argumentFunc();
foo = () => this.props.argumentFunc;

我如何传递回调到实例(fooInstance)稍后在类实例方法(callbackExecutor())内调用?

你试过了吗:

foo.getInstance().fooCallback = this.props.argumentFunc.bind(this)

最新更新