【问题标题】:How to pass props from mobx-observable to mobx-react observable?如何将道具从 mobx-observable 传递到 mobx-react observable?
【发布时间】:2018-03-06 23:26:23
【问题描述】:

我无法弄清楚 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')
);

【问题讨论】:

  • 我不太确定你在问什么。 It works for me.
  • 如果我有一个更复杂的应用程序,其中包含大约 10 个变量的存储区,那么将其注入每个组件是否会造成伤害?我应该编写从商店获取数据的不同注入模型吗?最好的方法是什么?再次感谢!!!
  • 没问题!如果您有一个带有 10 个变量的 CarStore,那么将它注入到需要这 10 个变量中的任何一个的每个组件中都没有问题。如果您有CarStoreGarageStore,并且您只需要特定组件中CarStore 中的变量,那么当然不需要将GarageStore 注入到该组件中。
  • 如果一个组件不需要全部 10 个变量怎么办?如果我只需要 CareStore 中的 1 个 var,我不必编写单独的提供程序,只需注入 10 个 var?或者这会破坏性能(你知道......所有的重新渲染......)。向您和整个 stackoverflow 社区大喊大叫,应该早点在这里问。节省了很多时间。

标签: javascript reactjs mobx mobx-react


【解决方案1】:

我最近没有做太多 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)

但最终您可能可以使用在 Provider 中传递的任何内容

在幕后,提供者可能只是通过 childContextTypecontextType 传递 context,而 HOC 将其记忆并映射到 props

【讨论】:

  • 干杯。我以为 mobx 会解决这个问题。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 2017-12-08
  • 2020-09-15
  • 2020-05-14
相关资源
最近更新 更多