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

时间:2017-08-17 13:14:36

标签: javascript reactjs mobx mobx-react

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

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

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

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')
);

1 个答案:

答案 0 :(得分:2)

我最近没有做太多的mobx并没有对此进行测试,但通常你会在某处提供一个提供商,然后使用@inject将商店作为道具传递

消费者信息:

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

@inject('information')
@observer
class Information extends React.Component {
  render(){
    {this.props.information.foo}
  }
}

模型级别 - 非常基本

import { observable, action } from 'mobx'

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

export new Information()

根提供商级别

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

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

// test it... 
setTimeout(() => {
  Information.foo = 'back to foo'
}, 2000)

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

在幕后,提供商可能只需通过context通过childContextTypecontextType,当HOC记忆并映射到props时。