在onClick()函数中获取最新值

问题描述 投票:0回答:4

我的应用程序是一个计数器。

import React, {useState} from "react";

 function App() {
  const [count, setCount] = React.useState(0);
  const add = () => {
    setCount(count+1)
    console.log(count) //here i want to get the updated count
  }
  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}

问题是我无法在count函数中获取add的值,我仅获取了先前的值。我知道这是因为useState是异步的。但是如何在不使用useEffect的情况下获取add函数内部的更新值?链接到沙箱:https://codesandbox.io/s/brave-feynman-k5b73?file=/src/App.js:0-377

reactjs
4个回答
0
投票

EDIT:正如@Drew Reese在评论中指出的那样,改变状态通常不是一个好主意。因此,您应该在变量之前复制并变异that。看到这个修改后的代码:

import React, {useState} from "react";

 function App() {
  const [count, setCount] = React.useState(0);
  const add = () => {
    let count2 = count
    setCount(++count2)
    console.log(count2) //here you get the updated count :)
  }
  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}

原始答案(这是不正确的,因为您仍然无法编辑常量)

您可以使用javascript中的预递增来执行此操作。本质上,它会增加值,但也会更改变量。

import React, {useState} from "react";

 function App() {
  const [count, setCount] = React.useState(0);
  const add = () => {
    setCount(++count)
    console.log(count) //here you get the updated count :)
  }
  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}

有关使用Javascript here进行预递增的更多信息。


0
投票

您可以导出默认的App功能组件

import React, { useState } from "react";

 function App() {
  const [count, setCount] = useState(0);
  const add = () => {
    setCount(count+1)
    console.log(count) //here i want to get the updated count
  }
  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}


export default App


0
投票

您必须使用useEffect来满足您的要求。因为setState没有回调功能。

import React, {useState,useEffect} from "react";

 function App() {
  const [count, setCount] = React.useState(0);

  useEffect(() => {
    console.log(count);
 },[count]);


  const add = () => {
    setCount(count+1)
    //console.log(count) //here you get the updated count :)
  }


  return (
    <div className="App">
      <h1>Hello {count}</h1>
      <button onClick={add}>ADD</button>
    </div>
  );
}

0
投票

如果要更新状态,而新状态取决于先前的状态,则应以这种方式更新它:

  const add = () => {
    setCount(prevCount => prevCount + 1);
  }

关于useEffect

useEffect(() => {
 console.log(count);
}, [count])

上面的代码在每次计数变化时都会运行,但是由于您说了有关分派动作的内容,所以您不想每次都可以有条件地执行操作时分派它:

useEffect(() => {
 if(count === 5) {
   console.log('Don't dispatch anything here');
 } else {
   console.log('Dispatch here');
 }
}, [count])
© www.soinside.com 2019 - 2024. All rights reserved.