【发布时间】:2019-09-29 02:08:34
【问题描述】:
我正在使用 React 和 mobx 来处理应用程序状态。
我正在使用通过外部存储(ajax 调用、过滤器或映射数组等)更改数据的转储组件
在表单中,当您必须通过 onChange 事件处理输入更改时,目前我在组件本身内部使用 observable 和 action。
这是一种不好的做法吗?或者我应该把所有的动作和可观察的数据放在一个外部状态中?
如果相反,这种做法是可以接受的,我该如何解决我必须重置本地可观察状态(如文本输入)以响应在外部存储中执行的 ajax 调用操作的情况? 我可以在动作存储中使用回调来放弃对组件内部动作的控制,如下例所示:
import React from 'react';
import { observer, inject } from "mobx-react";
import { observable, action } from "mobx";
@inject("rootStore")
@observer
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.externaStore = this.props.rootStore.contactStore
this.onChangeInput = this.onChangeInput.bind(this)
}
@observable text = ''
@action
onChangeInput(event) {
this.text = event.target.value
}
@action
resetForm() {
this.text = ''
}
render() {
return (
<form>
<div className="form-group">
<label htmlFor="input-text" className="control-label">Text input:
</label>
<input onChange={this.onChangeInput} type="text" value={this.text} id="input-text" name="input-text" className="form-control" />
</div>
<button onClick={() => this.externaStore.submitForm(this.text, this.resetForm)} className="btn btn-danger btn-xs" type="button" title="Aggiungi">
<i className="fa fa-save"></i> Aggiungi
</button>
</form>
)
}
}
class ExternalStore {
constructor(rootStore) {
this.rootStore = rootStore
this.service = rootStore.service
}
@observable textList = []
@action
submitForm(text, cb) {
this.service.doAjax('POST', '/api/text', JSON.stringify(text)).then(data => {
this.textList.push(text)
cb()
})
}
}
还有其他处理类似情况的最佳做法吗?
【问题讨论】:
标签: javascript reactjs state mobx