React.js具有基于其他状态的状态 [英] React.js having state based on other state

查看:72
本文介绍了React.js具有基于其他状态的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了React.js的一些问题,并且在调用setState()时没有立即设置状态。我不确定是否有更好的方法来解决这个问题,或者它是否真的只是React的一个缺点。我有两个状态变量,其中一个是基于另一个。 (原始问题的小提琴: http://jsfiddle.net/kb3gN/4415/ 你可以在日志中看到它不是单击按钮时立即设置。)

I'm running into some problems with React.js and the state not being immediately set when calling setState(). I'm not sure if there are better ways to approach this, or if it really is just a shortcoming of React. I have two state variables, one of which is based on the other. (Fiddle of original problem: http://jsfiddle.net/kb3gN/4415/ you can see in the logs that it's not set right away when you click the button)

setAlarmTime: function(time) {
  this.setState({ alarmTime: time });
  this.checkAlarm();
},
checkAlarm: function() {
  this.setState({
    alarmSet: this.state.alarmTime > 0 && this.state.elapsedTime < this.state.alarmTime
  });
}, ...

调用 setAlarmTime ,因为 this.state.alarmTime 没有立即更新,以下调用 checkAlarm 设置 alarmSet 基于之前的 this.state.alarmTime 的值,因此不正确。

When calling setAlarmTime, since this.state.alarmTime isn't updated immediately, the following call to checkAlarm sets alarmSet based on the previous value of this.state.alarmTime and is therefore incorrect.

我通过将 checkAlarm 的调用转移到 setState 的回调中来解决这个问题。 c $ c> setAlarmTime ,但是必须跟踪哪些状态实际上是正确的并尝试将所有内容都放入回调中似乎很荒谬:

I solved this by moving the call to checkAlarm into the callback of setState in setAlarmTime, but having to keep track of what state is actually 'correct' and try to fit everything into callbacks seems ridiculous:

setAlarmTime: function(time) {
  this.setState({ alarmTime: time }, this.checkAlarm);
}

还有更好的方法吗?在我的代码中有一些其他地方我引用我刚刚设置的状态,现在我不确定何时可以真正信任州!

Is there a better way to go about this? There are a few other places in my code which I reference state I just set and now I'm unsure as to when I can actually trust the state!

谢谢

推荐答案

是的, setState 是异步的,因此 this.state 不会立即更新。以下是用于批处理的单元测试 ,这可能解释了一些细节。

Yes, setState is asynchronous, so this.state won't be updated immediately. Here are the unit tests for batching, which might explain some of the details.

在上面的例子中, alarmSet 是从<$计算的数据c $ c> alarmTime 和 elapsedTime 州。一般而言,计算数据不应存储在对象的状态中,而应根据需要计算,作为渲染方法的一部分。有一节什么在交互性和动态用户界面文档的底部不应该进入状态?,它提供了不应该进入状态的这类事情的示例,以及哪些组件应该具有状态?部分解释了为什么这可能是一个好主意的一些原因。

In the example above, alarmSet is data computed from the alarmTime and elapsedTime state. Generally speaking, computed data shouldn't be stored in the state of the object, instead it should be computed as-needed as part of the render method. There is a section What Shouldn’t Go in State? at the bottom of the Interactivity and Dynamic UIs docs which gives examples of things like this which shouldn't go in state, and the What Components Should Have State? section explains some of the reasons why this might be a good idea.

这篇关于React.js具有基于其他状态的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆