[react闭包导致访问到旧的state值的处理方法]
import React, { useState, useMemo, useRef, useEffect } from "react"
function App() {
const [params, setParams] = useState({
size: 10,
page: 1,
})
//划重点 这里这里
const paramsRef = useRef(params)
useEffect(() => {
paramsRef.current = params
}, [params])
const list = useMemo(() => {
return [
{
key: "aaa",
name: "aily",
render: (item) => (
<button onClick={() => handleClick(item)}>{item.name}</button>
),
},
]
}, [])
const handleClick = (text) => {
console.log("params:", params)
console.log("paramsRef:", paramsRef)
console.log("text:", text)
}
return (
<div className="App">
<button
onClick={() => {
setParams({ size: 11, page: 2 })
console.log("params changes")
}}
>
change params
</button>
<p>
params size: {params.size}, page: {params.page}
</p>
<ul>
{list.map((item) => (
<li key={item}>{item.render(item)}</li>
))}
</ul>
</div>
)
}
export default App
网友评论