我的应用程序是一个计数器。
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
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进行预递增的更多信息。
您可以导出默认的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
您必须使用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>
);
}
如果要更新状态,而新状态取决于先前的状态,则应以这种方式更新它:
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])