假設我有以下狀態
const [page, setPage] = useState(1);
在這里,我有一個函式可以呼叫 api,然后對狀態進行一些操作,即
const getProducts=async()=>{
// i use the page state in an api call
...
//then afterward update the state
setPage(page 1);
}
我有一個函式 Refresh 將 State 重置為初始值并呼叫 getProducts 函式
const Refresh =()=>{
setState(1)
getProducts()
}
問題是當我呼叫重繪 函式時,頁面狀態不會重置/更新,因此使用我不想要的頁面呼叫 api 呼叫。這里的錯誤是什么,我該如何解決。在此先感謝
uj5u.com熱心網友回復:
添加getProducts允許您宣告頁面的 a 引數 ( currentPage)。如果你通過currentPage了,它會在setState. 如果沒有,它設定page 1:
const [page, setPage] = useState(1);
const getProducts = async(currentPage)=>{
// i use the page state in an api call
...
//then afterward update the state
setPage(currentPage ?? page 1);
}
const Refresh = () =>{
getProducts(1)
}
React 有一種方法可以避免批處理狀態,但這會影響 JSX 的渲染,而不是回呼中的值,例如:
顯示代碼片段
const { useState } = React
const { flushSync, createRoot } = ReactDOM
const Demo = () => {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const inc = () => {
flushSync(() => {
setA(a 1)
})
setB(a)
console.log(a)
}
return (
<div>
<button onClick={inc}>Increment</button>
<div>a {a} - {b} b</div>
</div>
)
}
createRoot(root).render(<Demo />)
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513483.html
