【发布时间】:2018-10-03 20:41:35
【问题描述】:
我正在创建一个通用的 react 组件,我在内部使用 mobx 来控制组件状态。我需要实现的是将所有业务逻辑保留在 Store 中,当用户更改 showSomething 道具时,商店应该知道它以便 fetchSomeStuffs 运行并更改 另一件事。
// Application using the component
@observer
class MyApplication extends React.Component {
@observable
showSomething = false;
changeThings = () => {
this.showSomething = true;
};
render() {
return (
<React.Fragment>
<button onClick={this.changeThings}>Change Show Something</button>
<MyComponent showSomething={showSomething} />
</React.Fragment>
);
}
}
class Store {
@observable
showSomething = false;
@observable
anotherThing = [];
@action
setShowSomething = value => {
this.showSomething = value;
};
// I'll dispose this later...
fetchSomeStuffs = autorun(() => {
const { showSomething } = this;
// Update some other stuffs
if (showSomething) {
this.anotherThing = [1, 2, 3];
} else {
this.anotherThing = [];
}
});
}
@observer
class MyComponent extends React.Component {
static propTypes = {
showSomething: PropTypes.bool
};
constructor() {
super();
this.store = new Store();
}
componentDidMount() {
const { setShowSomething } = this.store;
this.setSomethingDispose = autorun(() =>
setShowSomething(this.props.showSomething)
);
}
componentWillUnmount() {
this.setSomethingDispose();
}
render() {
return (
<Provider store={this.store}>
<MySubComponent />
</Provider>
);
}
}
@inject("store")
@observer
class MySubComponent extends React.Component {
render() {
const { showSomething, anotherThing } = this.props.store;
return (
<div>
MySubComponent
{showSomething && "Something is finally showing"}
{anotherThing.map((r, i) => {
return <div key={i}>{r}</div>;
})}
</div>
);
}
}
这是我找到的实现方式,所有逻辑都在 Store 中,我在主要组件的 componentDidMount 中使用 autorun 来始终保持store 的 showSomething 变量与 prop 相同。 我的疑问是,这是否是一种好的做法,或者是否有更好的方法来做到这一点?
【问题讨论】:
标签: reactjs mobx mobx-react