gpt4 book ai didi

reactjs - 在调用 setState() 之前直接改变状态是否可以?

转载 作者:搜寻专家 更新时间:2023-10-30 20:57:27 25 4
gpt4 key购买 nike

我正在使用轻量级 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 对象我也希望能够进行修改。

我改变状态的方式是否高于“危险”或“不良形式”???

更新

读了一些书,看起来这可能是一种错误的形式,可以使用 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 的更改属性。您可以阅读有关 react diffing algorithm 的更多信息在这里。

关于reactjs - 在调用 setState() 之前直接改变状态是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46250735/

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