發(fā)布于:2021-02-18 00:00:40
0
94
0
如果您在Json博客上關(guān)注我,您會(huì)知道我非常喜歡React,就像JavaScript開發(fā)領(lǐng)域中的其他所有人一樣。我正在使用的React應(yīng)用程序相對(duì)較小,它獲取請(qǐng)求以發(fā)送和接收數(shù)據(jù),僅渲染一組數(shù)據(jù),因此我根據(jù)組件的結(jié)果對(duì)組件進(jìn)行了大量的重置state 以及少量的state修改。 AJAX請(qǐng)求。讓我們看看我是怎么做的!
JavaScript
該state 對(duì)象沒有太多內(nèi)容,只有幾個(gè)屬性:
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;
}
// ....
}
您可能會(huì)收集到其中一個(gè)data 或error 將要有數(shù)據(jù),另一個(gè)將有數(shù)據(jù),null因此,我實(shí)質(zhì)上是在重置原始狀態(tài)值,然后填充data 或error。為此,我創(chuàng)建了一個(gè)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 });
使用散布運(yùn)算符合并默認(rèn)狀態(tài)和更新的狀態(tài)信息可保存來自多個(gè)setState 調(diào)用的多個(gè)渲染 。代碼也很短!
每個(gè)人都有自己的方法來處理自己的React應(yīng)用程序中的狀態(tài),因此我并沒有斷言這是通過少量更新即可重置狀態(tài)的最佳方法,但它對(duì)我來說效果很好。該代碼簡(jiǎn)短,描述性強(qiáng)且可重用!
作者介紹
熱門博客推薦