發(fā)布于:2021-02-18 00:00:40
0
87
0
如果您在Json博客上關(guān)注我,您會知道我非常喜歡React,就像JavaScript開發(fā)領(lǐng)域中的其他所有人一樣。我正在使用的React應(yīng)用程序相對較小,它獲取請求以發(fā)送和接收數(shù)據(jù),僅渲染一組數(shù)據(jù),因此我根據(jù)組件的結(jié)果對組件進(jìn)行了大量的重置state 以及少量的state修改。 AJAX請求。讓我們看看我是怎么做的!
JavaScript
該state 對象沒有太多內(nèi)容,只有幾個屬性:
class Controller extends React.Component {
// Added as a component property
defaultState = { data: null, error: null };
constructor(props) {
super(props);
// Set the default state immediately
this.state = this.defaultState;
}
// ....
}
您可能會收集到其中一個data 或error 將要有數(shù)據(jù),另一個將有數(shù)據(jù),null因此,我實質(zhì)上是在重置原始狀態(tài)值,然后填充data 或error。為此,我創(chuàng)建了一個resetStateWithUpdates如下所示的方法:
resetStateWithUpdates(stateUpdates = {}) {
// Rest operators ensure a new object with merged properties and values.
// Requires the "transform-object-rest-spread" Babel plugin
this.setState({ ...this.defaultState, ...stateUpdates });
}
And的用法如下:
// Ooops, fetch error!
// `data` implicitly reset to null
this.resetStateWithUpdates({
error: 'Fetching data failed! Please try again!',
});
// ... or we got good data!
// `error` implicitly reset to null
this.resetStateWithUpdates({ data });
使用散布運算符合并默認(rèn)狀態(tài)和更新的狀態(tài)信息可保存來自多個setState 調(diào)用的多個渲染 。代碼也很短!
每個人都有自己的方法來處理自己的React應(yīng)用程序中的狀態(tài),因此我并沒有斷言這是通過少量更新即可重置狀態(tài)的最佳方法,但它對我來說效果很好。該代碼簡短,描述性強(qiáng)且可重用!