react 数据重置_使用React进行状态重置和更新

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:

您可能会发现, dataerror将具有数据,另一个将为null ,因此我实质上是在重置原始状态值,然后填充dataerror 。 为此,我创建了一个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应用程序中的状态,因此我并没有断言这是通过少量更新即可重置状态的最佳方法,但它对我来说效果很好。 该代码简短,描述性强且可重用!

翻译自: https://davidwalsh.name/react-state

react 数据重置

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值