[英]Undefined parameter used within function
I am reading Redux tutorial and in a code snipped there is 'prevCounter' variable used without being initialized - '()' has no param within it.我正在阅读 Redux 教程,在代码片段中,使用了未初始化的“prevCounter”变量-“()”中没有参数。 How is it possible that prevCounter can be used within setCounter call?
prevCounter 怎么可能在 setCounter 调用中使用? Is prevCounter by default initialized with counter state thanks to arrow syntax used when calling setCounter and incremented prevCounter is implicitly returned?
由于调用 setCounter 时使用了箭头语法,prevCounter 默认使用计数器 state 初始化,并且隐式返回递增的 prevCounter?
Here is the snippet:这是片段:
function Counter() {
// State: a counter value
const [counter, setCounter] = useState(0)
// Action: code that causes an update to the state when something happens
const increment = () => {
setCounter(prevCounter => prevCounter + 1)
}
// View: the UI definition
return (
<div>
Value: {counter} <button onClick={increment}>Increment</button>
</div>
)
}
URL to the tutorial: https://redux.js.org/tutorials/essentials/part-1-overview-concepts URL 到教程: https://redux.js.org/tutorials/essentials/part-1-overview-concepts
The following code prevCounter => prevCounter + 1
is an Arrow Function .以下代码
prevCounter => prevCounter + 1
是箭头 Function 。 That means that when the function increment
(has no paramter) is called, it will trigger the setCounter
function with a callback function (the arrow function above). That means that when the function
increment
(has no paramter) is called, it will trigger the setCounter
function with a callback function (the arrow function above). This callback function takes the parameter prevCounter
, adds one to it and returns the value.此回调 function 接受参数
prevCounter
,将其加一并返回值。 Internally the setCounter
function stores somehow the current value and the value will be passed as the parameter prevCounter
to the callback function every time setCounter
is called. setCounter
function 在内部以某种方式存储当前值,并且每次调用setCounter
时,该值将作为参数prevCounter
传递给回调 function。
Just use counter
variable, like只需使用
counter
变量,例如
function Counter() {
const [counter, setCounter] = useState(0)
const increment = () => {
setCounter(counter + 1)
}
return (
<div>
Value: {counter} <button onClick={increment}>Increment</button>
</div>
)
}
Please try it and let me know. Hope it should do.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.