几个小时前,我刚刚听说过Mobx作为状态管理库。我决定尝试编写以下代码:
import React from 'react'
import { render } from 'react-dom'
import {observable} from 'mobx';
import {observer} from 'mobx-react';
var appState = observable({athlete_name:"Cy Young"});
@observer
export default class App extends React.Component
{
componentDidMount()
{
appState["athlete_name"] = "Babe Ruth"; // this variable/property will be loaded via a REST API http request
}
render() {
console.log(appState["athlete_name"]);
return (
<form>
<h1>{appState["athlete_name"]}</h1>
<textarea>{appState["athlete_name"]}</textarea>
<textarea defaultValue={appState["athlete_name"]} />
<textarea defaultValue="Babe Ruth" />
</form>
)
}
}
render(<App />, document.getElementById('app'))
但是由于某些原因,前两个textarea
打印Cy Young
。最后的textarea
,h1
和console.log(appState["athlete_name"])
按预期打印Babe Ruth
值。为什么两个文本区域中的Cy Young
没有被Babe Ruth
取代?我做错了什么?
答案 0 :(得分:2)