- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
想象一下这样的情况:
clickHandler(event) {
var that = this;
var cellIndex = event.target.id;
if(that.inProcess) return;
/* Temporarily clone state */
var cloneState = JSON.parse(JSON.stringify(this.state));
var currentCell = cloneState.gameCellArray[cellIndex];
currentCell.shown = true;
if (that.someCondition) {
that.inProcess = true;
setTimeout(function () {
currentCell.shown = false;
that.setState(cloneState);
that.inProcess = false;
}, 1000)
}
this.setState(cloneState);
}
clickHandler
中的第四个语句)可能会发生我没有得到状态的最新版本 - 因为有些
setState
来自之前调用
clickHandler
的调用待定,这是有效的假设吗?
setState
和回调参数),会更安全吗? (就没有不同步状态而言)。
clickHandler(event) {
var that = this;
var cellIndex = event.target.id;
if(that.inProcess) return;
that.setState(function(prevState, props){
var cloneState = JSON.parse(JSON.stringify(prevState));
var currentCell = cloneState.gameCellArray[cellIndex];
currentCell.shown = true;
if (that.someCondition) {
that.inProcess = true;
setTimeout(function () {
currentCell.shown = false;
// Do I need to take some measures here also?
that.setState(cloneState);
that.inProcess = false;
}, 1000)
}
return cloneState;
})
}
setTimeout
内部采取一些额外措施吗?还有(第二个重写版本)?
clickHandler
只是改变状态的函数 - 假设当用户单击某些按钮时被调用。
最佳答案
这是一个很长的答案。如果您不想全部阅读,请向下滚动到底部的 TLDR。
请注意,我描述了一些可能在 React 17+ 中更改的实现细节。这就是为什么我们的文档更加模糊,以便大多数人不会过分依赖实现细节。但在这种情况下,您似乎对它的真正运作方式特别感兴趣,所以我必须比我想要的更具体。
Now I got worried in theory that where I clone state (third statement in clickHandler) it can happen that I don't get the most recent version of the state - since some setState calls from previous invocation of clickHandler are pending, is it valid assumption?
this.state
在您自己更新状态 之前读取
是安全的。所以这段代码很好:handleClick() {
var something = this.state.something;
它会给你当前的状态。setState
,您不应该期望 this.state
立即更新。所以这段代码不起作用:handleClick(e) {
this.setState({ something: e.target.value });
var something = this.state.something; // Don't expect to get newValue here
Note: there is also another edge case pointed out in the comments: if you have several
onClick
handlers, the same pitfall applies: once you callsetState()
in a child event handler, you can’t rely onthis.state
being updated by the time the parent event handler runs. In fact it’s the reason this optimization is so useful: allsetState()
calls from a single browser event are batched, whether they happen in one or different components while the event bubbles.
setState
你已经知道你将它设置为:handleClick(e) {
var newValue = e.target.value;
this.setState({ something: newValue });
// There's no need to "read" something from state.
// Since you just set it, you already *know*
// what you set it to. For example:
doSomethingWith(newValue);
现在,有些情况下您想根据之前的状态 更新状态
。虽然您可以在事件处理程序中读取 this.state
,但这只能工作一次:handleIncrement() {
// This will increment once:
this.setState({ counter: this.state.counter + 1 });
// These won't work because this.state.counter isn't updated yet:
this.setState({ counter: this.state.counter + 1 });
this.setState({ counter: this.state.counter + 1 });
为了让你不必担心这样的情况, React 提供了一个不同的 setState()
重载,它接受一个函数 。该函数将在应用更新时接收当前状态,以便您可以安全地使用它。 React 将确保通过所有挂起的函数“线程化”当前状态:function increment(prevState) {
return { counter: prevState.counter + 1 };
}
// ...
handleIncrement() {
// Each function in the queue will receive the right state:
this.setState(increment);
this.setState(increment);
this.setState(increment);
// So this will increment three times.
从 React 16 及更早版本开始,此重载仅在您从同一事件处理程序多次调用 setState()
时才有用。但是,由于它也适用于其他情况,因此我们通常建议在任何时候您的 setState()
调用取决于当前状态 时使用它,这样您根本不需要考虑这一点。但是,如果您的代码在没有它的情况下工作,并且尝试重写它使其更加困惑,那么现在不要打扰。
setState()
的明显命令性质,以及我们推荐的更实用的方法。
setState()
一次(超时发生在以后),因此多次连续调用的陷阱不适用。
setState()
形式的第二种方法实际上没有正确使用它,使整个代码更加困惑。
setState()
的函数形式假定您传递给它的函数是
pure 。例如,这是一个纯函数:
function increment(prevState) {
return { counter: prevState.counter + 1 };
}
但是,您传递的函数不仅会计算下一个状态,还会安排超时、保留一部分状态、在原地改变它,并在超时内再次调用
setState
。这显然是
而不是 纯函数的行为方式。经验法则是
如果您不在 render()
内做某事,您也不应该在 setState()
更新程序函数 内做那件事。
setState()
一次,而您并没有尝试正确读取状态之后)。但是如果你确实想使用函数形式,你需要确保你传递的函数是纯函数。问题是:你把超时逻辑放在哪里?
componentDidUpdate()
生命周期钩子(Hook) 中。这样,只要满足必要的条件,它就会真正由状态更改触发——无论它发生在组件的哪个位置。例如,即使您有两个按钮触发相同的状态更改,它们都会导致
componentDidUpdate()
触发,并且它可以根据状态更改的方式运行超时逻辑。
I think that if you split the timeout-related part of this logic into the
componentDidUpdate
lifecycle hook, the code could be easier to understand. There might also be a better way to model the state itself. The matching game seems like a “state machine” with a few different valid states (nothing selected, one item selected and waiting, two right items selected, two wrong items selected).It might be worth encoding these possible game states more directly into your component state and think more carefully about how to represent them with objects. For example, it might be that instead of an array of cell values it is easier to think about an explicit state like:
{
openedCells: [1, 2], // array of ids
firstSelectedCell: 5, // could be null
secondSelectedCell: 7, // could be null
}and then implement conditional logic in
componentDidUpdate
, e.g.handleClick(e) {
// Are we waiting for a timeout? Reset it.
if (this.resetTimeout) {
clearTimeout(this.resetTimeout);
}
const id = ... // get it from target node, or bind event handler to ID in render()
this.setState(prevState => {
if (prevState.firstSelectedCell !== null && prevState.secondSelectedCell === null) {
// There is just one selected cell. We clicked on the second one.
return {
secondSelectedCell: id
};
}
// We are selecting the first cell
// (either because we clicked to reset both or because none were selected).
return {
firstSelectedCell: id,
secondSelectedCell: null
};
}
componentDidUpdate(prevState) {
if (prevState.secondSelectedCell !== this.state.secondSelectedCell) {
// We just picked the second cell.
if (isSamePicture(
this.state.secondSelectedCell,
this.state.firstSelectedCell
) {
// Same picture! Keep them open.
this.setState(prevState => {
// Add them both to opened cells and reset.
return {
firstSelectedCell: null,
secondSelectedCell: null,
openedCells: [
...prevState.openedCells,
prevState.firstSelectedCell,
prevState.secondSelectedCell
]
};
} else {
// Clear both in a second.
this.resetTimeout = setTimeout(() => {
this.setState({
firstSelectedCell: null,
secondSelectedCell: null,
});
}, 1000);
}
}Then, in the render method, you can show cells if either they are in
openedCells
or they arefirstSelectedCell
orsecondSelectedCell
.
this.state
调用之前读取 setState()
将为您提供当前状态。但是不要指望它会在 setState()
之后立即更新。 setState()
的函数重载防止了这个陷阱,但它要求传递的函数是纯函数。设置超时并不纯粹。 componentDidUpdate()
生命周期钩子(Hook)可能是设置依赖于状态的超时更好的地方。 关于javascript - 在这种情况下我需要使用 setState(function) 重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43428456/
我可以在传递给 this.setState() 的回调定义中显式调用 this.setState() 吗? this.setState( { openA:true }, () => {
我有一个从 api 获取数据的场景。在这种情况下,每当我从商店获取新值时,我的 componentWillReceiveProps() 就会被触发。 componentWillReceiveProps
在这个 componentDidUpdate 方法中,在执行 setState 将引号设置为从 fetch 返回的内容后,我必须使用回调再次执行 setState 以将 randomQuoteInde
正如 another question 中向我指出的那样,如果我在 setState、randomQuoteIndex() 中有一个不带参数的函数调用,并且该函数使用该 setState 中设置的状态
问题:当我使用 this.setState 并在回调中输出状态时,它根本不会改变,但是当我将 setstate 嵌套在 setstate 中时,它就会正常工作。 例子:这行不通- this.setSt
这个问题在这里已经有了答案: Why does setState take a closure? (2 个答案) 关闭 4 年前。 我对这两者的区别还是有点迷惑 isBusy = false;
当我使用 setState () 文本出现在调试控制台中.. setState() callback argument returned a Future. The setState() method
这个问题已经有答案了: Are 'Arrow Functions' and 'Functions' equivalent / interchangeable? (4 个回答) React - unca
之间的区别 - this.setState({value: 'xyz', name: 'john', color: 'orange'}) 对比 setValue('xyz'); setName('jo
之间的区别 - this.setState({value: 'xyz', name: 'john', color: 'orange'}) 对比 setValue('xyz'); setName('jo
我在运行代码时收到以下警告: Line 48: Do not mutate state directly. Use setState() react/no-direct-mutation-state
我是 React 的新手,我注意到我们使用 this.setState() 而不是 super.setState() 请我清楚地解释为什么我们用它来调用父类(super class)方法??示例: c
我一生都无法在我的 react 组件中传递这个 TypeError 。我已阅读所有相关主题并实现了几乎所有建议的修复,但均无济于事。 import React, { Component } from
我知道这可能是一个 JavaScript 问题而不是 React 问题,但我无法理解 React setState 的上述签名。 函数参数列表中的方括号和逗号有什么作用? 我知道如何将它与更新程序一起
是否可以在this.setState的回调中调用this.setState? 我正在制作一个 Roguelike Dungeon 并有一个设置,其中在 this.setState 的回调中使用了一个辅
我正在使用 react-navigation 进行路由。在一个组件上,我尝试设置 navigationOptions 以显示汉堡包按钮以打开和关闭侧边栏(抽屉)。所以 onPress 我试图为我的侧边
在之前的 React 版本中,我们可以在状态更改后执行代码,方法如下: setState( prevState => {myval: !prevState.myval}, () => { co
有一个 react 问卷组件,它将选定的答案添加到 this.state = {answer: []} 中,效果很好。同时,当用户更新答案时,它会添加为另一个对象。当questionID相同时,是否有
我正在使用 WebSocket 与我的服务器进行通信,并在我的 handleSubmit() 函数上输入一些值,并在此基础上与服务器进行通信并将我的状态更新为数据从 ws 收到。所以,第一次,一切都工
componentDidMount(prevProps, prevState, prevContext) { let [audioNode, songLen] = [this.refs.aud
我是一名优秀的程序员,十分优秀!