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

问题描述 投票:5回答:1

我无法弄清楚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')
);
javascript reactjs mobx mobx-react
1个回答
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)

但最终你可以使用你在提供者中传递的任何东西

在引擎盖下,当HOC记忆并映射到context时,提供者可能只是通过childContextTypecontextType传递props

© www.soinside.com 2019 - 2024. All rights reserved.