抱歉偽代碼。認為問題可以這樣理解。在一個可重現的例子中作業。
考慮以下偽代碼:
類 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()) 中呼叫?
uj5u.com熱心網友回復:
你有沒有嘗試過:
foo.getInstance().fooCallback = this.props.argumentFunc.bind(this)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475023.html
標籤:javascript 反应 还原
上一篇:通過單擊渲染具有不同狀態的組件
下一篇:不適用于React的JSX條件
