我正在使用轻量级 ORM 将我的 React 应用程序与外部服务连接...此包返回模型的对象并允许您直接对它们执行操作。虽然这真的很棒,但我很难弄清楚如何将这些对象包含在state
并仍然遵循 React 的“永远不要直接修改状态”租户。
如果我有一个更新帐户名的组件,这样做可以接受吗?
interface IAppState {
account: Account
}
class App extends React.Component<{}, IAppState> {
constructor(props) {
super(props);
this.state = {
account: new Account()
}
}
//set the new name and update the external service
public updateAccount = (newName: string)=>{
account.name = newName; //REDFLAG!!!
acc.update().then(()=>{
this.setState({ account: this.state.account })
})
}
//retrieve our account object from external service
public componentDidMount() {
const qParams = queryString.parse(window.location.search);
Account.get(qParams.externalId).then((acc)=>{
this.setState({account: acc})
})
}
render() {
return <NameEditor handleClick={this.updateAccount} account={a} />
}
}
我想我可以通过启动一个空白的 ORM 对象、复制属性、发送更新然后设置状态来避免改变状态,但这似乎是一个很大的痛苦。特别是因为这些 ORM 对象可以包含我想要的子 ORM 对象也希望能够修改。
我改变状态的方式是否高于“危险”或“不良形式”???
Update
做了一些阅读,这绝对看起来可能是一种不好的形式,并且可以使用react/addons
... 但是,如果 ORM 调用对对象有副作用怎么办??例如,调用insert
设置对象的外部 id 字段。
public updateAccount = (newName: string)=>{
//account.name = newName; //REDFLAG!!!
// You can use the below code to update name after it is updated
// on server.
// This will work because the object being passed here
// will be merged with Component state.
acc.update().then(()=>{
this.setState({account: {name : newName}})
})
}
不建议直接修改状态,因为 React 不会知道更改,也不会导致重新渲染。
所有的差异都发生在虚拟 DOM 上,并且 React 只更新浏览器 DOM 的更改属性。您可以阅读更多有关反应差异算法 https://facebook.github.io/react/docs/reconciliation.html here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)