将调度函数传递给另一个实例 属性 作为稍后执行的回调
pass dispatch function to another instance property as callback to execute later on
抱歉伪代码。认为问题可以这样理解。在可重现的示例中工作。
考虑以下伪代码:
Class 富:
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
为null。
我试过了:
foo = this.props.argumentFunc();
foo = this.props.argumentFunc;
foo = () => this.props.argumentFunc();
foo = () => this.props.argumentFunc;
如何将回调传递给实例 (fooInstance
),以便稍后在 class 实例方法 (callbackExecutor()
) 中调用?
你试过了吗:
foo.getInstance().fooCallback = this.props.argumentFunc.bind(this)
抱歉伪代码。认为问题可以这样理解。在可重现的示例中工作。
考虑以下伪代码:
Class 富:
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
为null。
我试过了:
foo = this.props.argumentFunc();
foo = this.props.argumentFunc;
foo = () => this.props.argumentFunc();
foo = () => this.props.argumentFunc;
如何将回调传递给实例 (fooInstance
),以便稍后在 class 实例方法 (callbackExecutor()
) 中调用?
你试过了吗:
foo.getInstance().fooCallback = this.props.argumentFunc.bind(this)