Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 函数中使用的未定义参数_Javascript_Reactjs - Fatal编程技术网

Javascript 函数中使用的未定义参数

Javascript 函数中使用的未定义参数,javascript,reactjs,Javascript,Reactjs,我正在阅读Redux教程,在一段截取的代码中,使用了未初始化的“prevCounter”变量-“()”中没有参数。如何在setCounter调用中使用prevCounter?由于调用setCounter时使用的箭头语法,prevCounter是否默认使用计数器状态初始化,并且隐式返回递增的prevCounter 以下是片段: function Counter() { // State: a counter value const [counter, setCounter] = useSt

我正在阅读Redux教程,在一段截取的代码中,使用了未初始化的“prevCounter”变量-“()”中没有参数。如何在setCounter调用中使用prevCounter?由于调用setCounter时使用的箭头语法,prevCounter是否默认使用计数器状态初始化,并且隐式返回递增的prevCounter

以下是片段:

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>
  )
}
函数计数器(){
//状态:计数器值
常量[计数器,设置计数器]=使用状态(0)
//操作:当发生某些事情时导致状态更新的代码
常量增量=()=>{
设置计数器(prevCounter=>prevCounter+1)
}
//视图:UI定义
返回(
值:{counter}增量
)
}

教程的URL:

只需使用
计数器
变量,如

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.
函数计数器(){
常量[计数器,设置计数器]=使用状态(0)
常量增量=()=>{
设置计数器(计数器+1)
}
返回(
值:{counter}增量
)
}
请试一试,让我知道。希望它可以。

以下代码
prevCounter=>prevCounter+1
是一个。这意味着当调用函数
increment
(没有参数)时,它将触发带有回调函数(上面的箭头函数)的
setCounter
函数。此回调函数接受参数
prevCounter
,向其添加一个参数并返回值。在内部,
setCounter
函数以某种方式存储当前值,每次调用
setCounter
时,该值将作为参数
prevCounter
传递给回调函数。

因此,我的问题是:在这种情况下,此行“setCounter(prevCounter=>prevCounter+1)”是否正确?这是一个教程的片段-不是我自己的,所以我认为它是正确的。我尝试了,它成功了!那么prevCounter是由setCounter函数用计数器状态值在内部初始化的?是的,它是由setCounter函数用计数器状态值初始化的。当使用箭头函数时,我们可以省略{括号}和(括号)以及“返回”。参考:参考: