gpt4 book ai didi

javascript - 在 MobX 中使用 React 时可以直接修改状态吗?

转载 作者:行者123 更新时间:2023-11-28 18:05:08 24 4
gpt4 key购买 nike

我不应该这样做的唯一原因是让 react 更新 View 。 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'));

最佳答案

最好完全绕过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'));

关于javascript - 在 MobX 中使用 React 时可以直接修改状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42830686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com