mobx react action binding

こ雲淡風輕ζ 提交于 2020-02-02 13:11:28

问题


For those who has written apps with mobx + react, I'm wondering if there's a better way to handle context issue (eg. this. returns undefined in mobx store) when using onClick event handler inside a react component w/ inject & observer.

I have been writing the handler like onClick={actionFromStore.bind(this.props.theStore)} to resolve that issue, but it seems like there should be more concise way to do this that I'm not aware of.

I'm not a mobx expert, any advice would be appreciated!

The actions here are async fetch requests


回答1:


You can either use @action.bound decorator:

@action.bound
doSomething(){

    // logic

}

or use labmda function which will preserve the context:

@action
doSomething = ()=> {

    // logic

}



回答2:


Since there is 2018, the best practice in React apps development is to use lambda functions as class properties instead of class methods.

The lambda function as class property resolves all issues that can happen with context. You don't have to bind methods to the specific context, if using it.

For example, you working with this in some class method:

export default class SomeClass {
    myProp = "kappa"

    myMethod() {
        console.log(this.myProp)
    }
}

In this case, if you will use it, e.g., like some event listener, this will be unexpectedly (actually, more than expected) change from SomeClass instance to other value. So, if you using class methods, you should modify you code like this:

export default class SomeClass {
    constructor() {
        this.myMethod = this.myMethod.bind(this)
    }

    myProp = "kappa"

    myMethod() {
        console.log(this.myProp)
    }
}

In constructor you are binding your class method to context of SomeClass instance.

The best way to avoid this kind of unnecessary code (imagine, that you have 10+ of this type of methods - and you should bind each of them), is to simply use lambda functions:

export default class SomeClass {
    myProp = "kappa"

    myMethod = () => {
        console.log(this.myProp)
    }
}

That's it! Lambda functions have no context, so this will always point to the SomeClass instance. So, now you can decorate you class property as you wish:

export default class SomeClass {
    myProp = "kappa"

    @action
    myMethod = () => {
        console.log(this.myProp)
    }
}

Note, that if you are using Babel, you have to use transform-class-properties plugin.

This question is more related to the core of JavaScript, so I advise you to read this MDN article for more information about this behavior.

Hope, this was helpful!



来源:https://stackoverflow.com/questions/54121988/mobx-react-action-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!