Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mobx in React #2

Open
SuperAL opened this issue Nov 25, 2019 · 0 comments
Open

Mobx in React #2

SuperAL opened this issue Nov 25, 2019 · 0 comments

Comments

@SuperAL
Copy link
Owner

SuperAL commented Nov 25, 2019

Mobx in React

Notes taken down from watching the tutorial Manage Complex State in React Apps with MobX from @mweststrate on @eggheadio

Sync the UI with the app state using MobX observable and observer in React

just like using state and setState:

@observer
class Counter extends Component {
    @observable count = 0
    render() {
        return (
            <div>Counter: {this.count}</div>
        )
    }
}
and we can change the count value by this.count++ or this.count--

above equals below:

let store = observable({
    count: 0
})

@observer
class Counter extends Component {
    render() {
        return (
            <div>Counter: {store.count}</div>
        )
    }
}
and we can change the count value by store.count++ or store.count--

Analyze React components with MobX-React devtools

@observer on a class is like a sugar syntax for making the render function in the class component a reaction which will happen whenever a related observable value is changed.

import DevTools from 'mobx-react-devtools'

and use it in the render function
<DevTools></DevTools>

then you will see three buttons shown on your component

three functions: see which component gets updated; see the observer and observable relations; see more detailed information in the console

Derive computed values and manage side effects with MobX reactions

Core parts: Actions, observable state, computed values, and reactions.

Computed values are not allowed to produce side effects like changing state or making network requests. 

By default MobX doesn't try to keep computed values up to date. The reason for that is that MobX always tries to defer the computation of computed properties until they are needed by IO and side effects.

If you ask for a value which has been observed by reaction(values used in the last computed path), you can just get the value because it has cache. If you ask for a value which has not been observed or not used in the last computed path, it will be reevaluated and return the latest value.

If b is computed from a, but b is not observed, then whenever a updates its value, b will not update, unless you directly ask for the value of b, then it will be evaluated.
a 会影响到 b 的值的计算,但是 b 未被 observe,因此 a 更新值并不会导致 b 的值更新,除非主动调用 b,就能获取到 b 的最新值

Use observable objects, arrays, and maps to store state in MobX

class T {
    @observable unit = 'C'
}

equals 

class T {
    constructor() {
        extendObservable(this, {
            unit: 'C'
        })
    }
}

equals

const t = observable({
    unit: 'C'
})

const t = observable([])
Array.isArray(t) false
Array.isArray(t.slice()) true
const t = observable(asMap({
    'a': 1,
    'b': 2
}))
t.entries().map(([key, value]) => {
    return key + value
})

const boxed = observable(42)
boxed.get()
boxed.set(53)

Use MobX actions to change and guard state

transaction(() => {
    t.unit = 'K';
    t.unit = 'F';
})

action automatically apply the transaction function for grouping state modifications

useStrict(true)

then you cannot modify state in any other ways but using actions

@action('update unit')

it will show up in the console once we enabled the change log in mobx dev tools.

Pass observable data through props in MobX

stateless component(function component)

const App = observer(({temperatures}) => (
    <ul>
        {temperatures.map(t => <li>
            {t.temperature}
        </li>)}
    </ul>
))

Make each <li> an independent component so that each render update can happen efficiently.

Handle user input and asynchronous actions with MobX

Nothing new.

Connect MobX observer components to the store with the React Provider

import { Provider } from 'mobx-react'
const temp = observable([]) // some kind of store
<Provider temperatures={temp}></Provider>

const t = observable(['temperatures'], ({temperatures}) => (
    <ul>
        ...
    </ul>
))

@observer(['temperatures']) // get temperatures from props without explicitly passing it from the parent component
class inputView extends React.Component {
    ...
    @action
    doSomething = () => {
        this.props.temperatures...
    }
}

Write custom MobX reactions with when and autorun

when(() => {
    return TrueOrFalse()
}, () => {
    doSomethingOnce() // when parameter one return true
})

const t = observable({})
autorun(() => {
    doSomethingUsingObservedValue(t) // run at once and whenever observed value changes
})
@SuperAL SuperAL changed the title [Learning notes] Mobx in React Mobx in React Nov 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant