将React与MobX一起使用时,我可以直接修改状态吗?

时间:2017-03-16 09:59:02

标签: javascript reactjs mobx mobx-react

我不应该这样做的唯一原因是让反应更新视图。 https://facebook.github.io/react/docs/state-and-lifecycle.html#using-state-correctly
  但似乎MobX-react为我做了这些肮脏的工作。我只需要将this.state标记为可观察,并且一切都按预期工作。有什么缺点吗?我不想把所有州都扔进一家大商店。

JSFiddle link

代码:

const {observable, computed} = mobx;
const {observer} = mobxReact;
const {Component} = React;

@observer
class Form extends React.Component{
    @observable state = {
        username: '',
        password: '',
    };

    constructor(...args) {
        super(...args);
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    render() {
        return  <form onSubmit={this.handleSubmit}>
                    <label>
                    Name:
                    <input type="text" value={this.state.username} onChange={event => this.state.username = event.target.value} />
                    </label>
                    <div>username: {this.state.username}</div>
                    <input type="submit" value="Submit" />
                </form>;
    }

    handleSubmit(event: Event) {
        event.preventDefault();
        console.log(this.state.username);
    }
}

ReactDOM.render(
    <div>
        <Form />
        <mobxDevtools.default />
    </div>
, document.getElementById('mount'));

2 个答案:

答案 0 :(得分:2)

最好完全绕过state并将可观察数据直接放在课堂上。

示例(JS Bin

const {observable, computed} = mobx;
const {observer} = mobxReact;
const {Component} = React;

@observer
class Form extends React.Component{
    @observable username = '';
    @observable password = '';

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this)
    }

    render() {
        return <form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input type="text" value={this.username} onChange={event => this.username = event.target.value} />
            </label>
            <div>username: {this.username}</div>
            <input type="submit" value="Submit" />
        </form>;
    }

    handleSubmit(event: Event) {
        event.preventDefault();
        console.log(this.username, this.password);
    }
}

ReactDOM.render(
    <div>
        <Form />
    </div>
, document.getElementById('mount'));

答案 1 :(得分:1)

您可以将其命名为form而不是state,它不会关心,它会绕过React的setState和重新呈现机制。除了将状态更新合并到组件之外,React setState还会告诉您的组件重新呈现。 React组件有forceUpdate

MobX也会同时执行这两项工作,通过更新observable,您还会向已连接的observer组件发送消息以进行更新。拥有一个中央状态存储是React的既定模式。