[英]React.JS Best Way to Back Up State
在我的應用程序中,當一個組件被渲染時,我的狀態以某種方式被破壞,所以我把狀態放在類之外,我將每個setState
更改為我自己定義的更改狀態的方法。
這是我的代碼
let theState = {//the state properties}
class Foo extends Component{
//the method is used to change the state, and setState to trigger rendering
updateState(data){
theState = {...theState,...data}
console.log('sate update',{theState})
this.setState(theState)
}
}
這沒關系,但問題是當我們談論可重用性時,我不想在每個組件上都編寫updateState
方法,有沒有更好的解決方案?
要在基於類的組件中使用狀態,您需要使用構造函數,然后使用this.state = {}
。 然后,您可以通過在組件中調用this.setState({})
來更新狀態。 舉個例子:
class Something extends React.Component {
constructor(props) {
super(props);
this.state = {foo: "thing"};
}
或者,如果您使用 React ^16,則可以使用功能組件和 React 鈎子。 在這種情況下,您的代碼將類似於:
const Foo = () -> {
const [data, setdata] = React.useState()
const updateState = (update) => {
setData({...data, ...update}) //assuming it is an update or
setData({update}) //assuming you want to replace the values
}
}
狀態僅適用於本地(組件)級別,除非您引入了像 Redux 這樣的應用程序狀態管理器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.