如何将mobx-observable中的道具传递给mobx-react observable?

joe*_*euk 5 javascript reactjs mobx mobx-react

我无法弄清楚mobx-react ......

如何将mobx observable中的道具传递给mobx反应观察者?

下面的代码不起作用,但我觉得应该这样.谁能告诉我出了什么问题?

let mobxData = observable({information: "this is information"});

@observer class Information extends React.Component {
    render() {
        console.log(this.props.mobxData.information);
        return (
            <h1>class: {this.props.mobxData.information}</h1>
        )
    }
};

const StatelessInformation = observer(({mobxData}) => {
    console.log(mobxData.information);
    return <h1>stateless: {mobxData.information}</h1>
});

ReactDOM.render(
    <div>
        <Information/>
        <StatelessInformation/>
    </div>,
    document.getElementById('app')
);
Run Code Online (Sandbox Code Playgroud)

Dim*_*off 2

我最近没有做过太多的 mobx,也没有测试过这个,但通常你会在某个地方有一个提供者,然后使用来@inject传递商店作为道具

信息消费者:

import { observer, inject } from 'mobx-react'

@inject('information')
@observer
class Information extends React.Component {
  render(){
    {this.props.information.foo}
  }
}
Run Code Online (Sandbox Code Playgroud)

模型级别 - 非常基础

import { observable, action } from 'mobx'

class Information {
  @observable foo = 'bar'
  @action reset(){
    this.foo = 'foo'
  }
}

export new Information()
Run Code Online (Sandbox Code Playgroud)

根提供商级别

import { Provider } from 'mobx-react'
import Information from ./information'

<Provider information={Information}>
  <Information />
</Provider>

// test it... 
setTimeout(() => {
  Information.foo = 'back to foo'
}, 2000)
Run Code Online (Sandbox Code Playgroud)

但最终你可能可以使用你在提供者中传递的任何内容

在幕后,提供者可能只是context路过childContextTypecontextType当 HOC 记住它并映射到props.