I am using mobx
and react
in a web application and I want to find a way to pass mobx
store state to a stateless component. Below is my current component source code:
import React from 'react'; import Panel from './Panel'; import {inject, observer} from 'mobx-react'; @inject(allStores => ({ form: allStores.store.form, })) @observer export default class Creator extends React.Component { connect() { console.log(this.props.form); }; render() { return ( <Panel form={this.props.form} connect={this.connect.bind(this)}/> ); } };
How can I change it to be stateless? I tried below code but didn't work:
const Creator = ({form}) => { const connect = ()=>{ console.log('xxxx,', form); } return ( <Panel form={form} connect={connect}/> ); } export default observer(Creator);
when I run above code, I got undefined
value for form
on the connect
method. How can I inject the store into stateless component? I tried to use @inject
on top of stateless component, but got a syntax error.
import React from 'react'; import Panel from './Panel'; import {inject, observer} from 'mobx-react'; @inject(allStores => ({ form: allStores. store. form, })) @observer export default class Creator extends React. Component { connect() { console.
Note that mobx-react fully repackages and re-exports mobx-react-lite , including functional component support. If you use mobx-react , there is no need to add mobx-react-lite as a dependency or import from it anywhere. Note: observer or React.
The store injection pattern was popularized by the mobx-react library. It refers to a now obsolete way of accessing the MobX stores across the component tree. It was introduced because the React legacy context was rather awkward to use. We are in 2019 now and we don't need injections anymore (kids, don't do drugs).
With the introduction of the new Context API, there is no need to use Provider pattern with MobX and you can now just use the React Context API.
inject
returns a function that you can use on a observer functional component:
var Example = inject("myStore")(observer((props) => { // ... }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With