在我的increaseCount方法中,我有3种不同的方法来增加计数。我认为第一个方法可以使用两次,但它不起作用,因为它似乎合并了回调中的 setState 。使用回调函数的正确方法是什么?为什么箭头表示法有效? prevState.count 是如何定义的?它永远不会设置为 0
import React from "react";
import { render } from "react-dom";
const styles = {
fontFamily: "sans-serif",
textAlign: "center"
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increaseCount() {
console.log(this);
this.setState({ count: this.state.count }, function() {
this.setState({ count: this.state.count + 1 });
});
this.setState({ count: this.state.count + 1 });
this.setState(prevState=>({ count: prevState.count + 1 }));
}
render() {
return (
<div style={styles}>
<div>
<button onClick={() => this.increaseCount()}>Increase</button>
</div>
<h2>{this.state.count}</h2>
</div>
);
}
}
render(<App />, document.getElementById("root"));
最佳答案
据我所知,只有第三种方法才是增加状态值的正确方法。回顾你的尝试:
this.setState({ count: this.state.count }, function() {
this.setState({ count: this.state.count + 1 });
});
此代码段是多余的(您将计数设置为相同的值),然后当状态更改完成时,您可以通过向 this.state.count
加 1 来增加计数。虽然这在这里很好,但您可以一开始就这样做(如下一个片段所示)。
下一个:
this.setState({ count: this.state.count + 1 });
更好,但是 setState
方法是异步的,因此实际的状态更改要稍后才会发生。这意味着这在大多数情况下都有效,但如果您调用它两次,它不会增加两倍,因为this.state.count
尚未更新当第二次调用发生时。
最后,您的最后一次尝试看起来很完美:
this.setState(prevState=>({ count: prevState.count + 1 }));
这使用了函数 setState
语法,其中 React 将为您的回调函数提供当前状态,并且您应该读取它并返回所需的新状态。使用这种风格,您可以调用它两次(或任意次数),并且每次调用都会适本地增加计数。
解决您的其他一些问题:
it seems to merge the setState in the callback.
正确。来自下面链接的文档:
<小时/>React may batch multiple setState() calls into a single update for performance.
What's the proper way to use a callback function and why does the arrow notation work?
函数 setState
是一个新的 React 功能。箭头函数很好,但不是必需的(除非您在回调中访问 this
)。来自他们的documentation here :
<小时/>To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
// Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
We used an arrow function above, but it also works with regular functions:
// Correct this.setState(function(prevState, props) { return { counter: prevState.counter + props.increment }; });
How is prevState.count being defined? It is never set to 0
它在构造函数中被设置为零。该行:
this.state = {
count: 0
};
是最初设置它的内容。从那时起,当前状态(无论是什么)将传递给您的 setState
回调函数。
抱歉,这个答案在我意识到之前就失控了。希望这会有所帮助,LMK,如果我没有捕获要点或者还有更多问题
关于javascript - 使用回调函数和理解箭头表示法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415229/