美文网首页
react闭包导致访问到旧的state值的处理方法

react闭包导致访问到旧的state值的处理方法

作者: Spidd | 来源:发表于2020-12-10 10:15 被阅读0次

    [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
    
    

    相关文章

      网友评论

          本文标题:react闭包导致访问到旧的state值的处理方法

          本文链接:https://www.haomeiwen.com/subject/apylgktx.html