[英]Unidirectional Data Flow in React with MobX
我正在尝试使用MobX和React设置项目体系结构,并且想知道是否将以下内容视为“不错”。 我不希望这个问题最终成为另一个问题,“这是个人喜好,因此,这个问题不属于这里……我们都可以同意,有些事情确实很糟糕。
所以我在考虑只拥有一个看起来像这样的Store.js
文件:
import { observable, action, useStrict } from 'mobx';
useStrict(true);
export const state = observable({
title: ''
});
export const actions = {
setTitle: action((title) => {
state.title = title;
})
};
注意 :所有应用程序状态都将处于state
,只有一个存储。
然后,在根组件aka App.js
使用state
, App.js
所示:
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { state } from './Store';
import DisplayTitle from './components/DisplayTitle/DisplayTitle';
import SetTitle from './components/SetTitle/SetTitle';
class App extends Component {
render() {
return (
<div className="App">
<DisplayTitle title={state.title}/>
<SetTitle />
</div>
);
}
}
export default observer(App);
很明显,我的应用程序中会包含很多组件,但是没有一个组件会直接从Store.js
读取state
。 只有我的App.js
会导入状态并将其传递到组件树下。
另一个注意事项 :我不太确定为什么其他组件不能直接从Store.js
读取状态...
DisplayTitle
组件就是这种情况:
import React, { Component } from 'react';
class DisplayTitle extends Component {
render () {
return (
<h1>{this.props.title}</h1>
);
}
}
export default DisplayTitle;
但是,即使没有其他组件可以直接导入state
( App.js
除外),任何组件都可以从Store.js
导入actions
以使state
发生突变。
例如在SetTitle
组件中:
import React, { Component } from 'react';
import { actions } from './../../Store';
class SetTitle extends Component {
updateTitle (e) {
actions.setTitle(e.currentTarget.value);
}
render () {
return (
<input onChange={this.updateTitle} type='text'/>
);
}
}
export default SetTitle;
是否有任何缺陷或其他明显的原因导致这种方法不是最佳选择? 我希望收到所有反馈!
你缺少一些东西
在根级别:
import { Provider } from 'mobx-react'
...
<Provider state={state}>
<Other stuff />
</Provider>
在组件级别:
import { inject } from 'mobx-react'
@inject('state')
class Foo ... {
handleClick(){
this.props.state.setTitle('foo')
}
render(){
return <div onClick={() => this.handleClick()}>{this.props.state.title}</div>
}
}
您只能在提供程序中粘贴接口actions={actions}
并将其注入,以确保子代可以调用您的API方法来改变状态并使状态自下而上流动。 尽管如果直接对其进行突变,则不会发生任何副作用,因为所有组件都将在渲染树中进行willReact
和更新-通量更willReact
推理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.