react 数据重置
If you follow me on Twitter, you'll know that I've taken a real liking to React, as has seemingly everyone else in the JavaScript development world. The React app I'm working on is relatively small, making fetch requests to send and receive data, rendering only one set of data, so I'm doing a lot of resetting of component state
along with a small state
modification depending on the result of the AJAX request. Let's have a look at how I do it!
如果您在Twitter上关注我 ,您会知道我非常喜欢React ,就像JavaScript开发领域中的其他所有人一样。 我正在使用的React应用相对较小,仅获取一组发送和接收数据的请求 ,仅渲染一组数据,因此我根据结果对组件state
进行了很多重置以及小的state
修改的AJAX请求。 让我们看看我是怎么做的!
JavaScript (The JavaScript)
There's not much to the state
object -- just a few properties:
state
对象没有太多-仅有一些属性:
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;
}
// ....
}
You can probably gather that either data
or error
will have data, the other will be null
, thus I'm essentially resetting the original state value and then populating data
or error
. To do this I've created a resetStateWithUpdates
method that looks as follows:
您可能会发现, data
或error
将具有数据,另一个将为null
,因此我实质上是在重置原始状态值,然后填充data
或error
。 为此,我创建了一个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 is used like:
和使用像:
// 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 });
Using the spread operator to merge the default state and updated state information saves multiple renders from multiple setState
calls. The code is also very short!
使用散布运算符合并默认状态和更新的状态信息可保存来自多个setState
调用的多个渲染。 代码也很短!
Everyone has their own way to handle state within their React apps, so I'm not asserting this is the best method for resetting state with a small update, but it works wonderfully for me. The code is short, descriptive, and reusable!
每个人都有自己的方法来处理自己的React应用程序中的状态,因此我并没有断言这是通过少量更新即可重置状态的最佳方法,但它对我来说效果很好。 该代码简短,描述性强且可重用!
react 数据重置