让我们在带有React和React Router的应用程序中使用这样的类。
@observer class Module1 extends React.Component {
constructor (props) {
super(props);
//...
}
componentWillMount(){
//...
}
method(){
//...
}
otherMethod(){
//...
}
render() {
return (
<ChildComp bars={this.props.bars}/>}
);
}
}
让我们以这样的状态为例
state = observable({
module1:{
bars:{
//...
}
},
module2:{
foos:{
//...
}
}
})
Module1组件的加载方式如下:
//index.js
render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path='/map' component={Module1} >
<Route path="/entity/:id" component={SubModule}/>
</Route>
<Route path='/map' component={Module2} >
</Route>
</Router>,
document.getElementById('render-target')
);
如何将props module1.bars
传递给Module1组件?在redux中,我会使用<provider>
和redux-connect
,但在Mobx.js中我对此有点迷惑。
发布于 2016-03-08 02:23:41
首先,这是一个使用MobX、React和react-router执行路由的简单示例应用程序:https://github.com/contacts-mvc/mobx-react-typescript
一般来说,就我个人而言,我喜欢显式地将所有相关的存储作为显式道具传递给我的组件。但您也可以使用像Ryan这样的包,使用React上下文机制将您的存储传递给组件,类似于Redux connect (请参阅此app以获取示例)。
一旦在组件中有了存储,就可以在ComponentWillMount中解析路由参数,并相应地更新存储。
这基本上应该是全部:)但是,如果我没有回答任何问题,请让我知道。
发布于 2016-08-06 18:07:32
在撰写本文时,mobx-react提供了一个(实验性的) Provider
(组件)和inject
(高阶组件)来将属性传递给下面的组件层次结构。
在上面,您可以使用Provider
组件来传递所有相关信息。在幕后,使用了React上下文。
import { Provider } from 'mobx-react';
...
import oneStore from './stores/oneStore';
import anotherStore from './stores/anotherStore';
const stores = { oneStore, anotherStore };
ReactDOM.render(
<Provider { ...stores }>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="/" component={SomeComponent} />
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
在SomeComponent
中,您可以使用inject
HOC来检索传递的属性:
import { observer, inject } from 'mobx-react';
...
const SomeComponent = inject('oneStore', 'anotherStore')(observer(({ oneStore, anotherStore }) => {
return <div>{oneStore.someProp}{anotherStore.someOtherProp}</div>;
}))
export default SomeComponent;
[免责声明:我在MobX React: Simplified State Management in React中写过它,您可以看到一个使用SoundCloud应用程序接口的minimal boilerplate application。]
发布于 2016-04-26 22:18:54
看看react-tunnel吧。它提供了一个Provider
组件和inject
装饰器(工作方式类似于redux中的connect
)。
https://stackoverflow.com/questions/35850871
复制相似问题