Map data using useRef Hook

核能气质少年 提交于 2020-07-10 07:31:12

问题


I am following this: Merge two JSON data into one with particular key values

Now, I added an useEffect() hook. How can I make use of useRef to store my result? This is an asynchronous function.

const App = (props) =>{
    let result = useRef ()
    useEffect(()=>{
      return()=>
        (result.current = [courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, 
        {[c.court_id] : q[i].color}))))
      }.[someTrigger])
   return(
        <ul>
           {result.current.map(r => (
           <li>
             Court id - {r.court_id} | Ball colour - {r.color}
           </li>
      ))}
    </ul>
)
}

Now my {r.court_id} and {r.color} are empty.

Things I have tried:

const App = (props) =>{
       [result, setResult] = useState({})
        useEffect(()=>{
          setResult([courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, 
            {[c.court_id] : q[i].color}))))
          }))
       return(
            <ul>
               {result.map(r => (
               <li>
                 Court id - {r.court_id} | Ball colour - {r.color}
               </li>
          ))}
        </ul>
)
}

error: TypeError: result.map is not a function


回答1:


As per your render statement, resolve data like below

If you choose useState option

 useEffect(() => {
    const final = [courtdata, balldata].reduce((p, q) => p.map((c, i) => Object.assign({}, c, {color: q[i].color})));
    setResult(final);
  }, []);


Example https://codesandbox.io/s/react-hooks-usestate-shz9v




回答2:


useEffect hook execute after component mounted, and useRef is to access some dom component.

I think what you need is useState.

const [result, setResult] = useState({});


来源:https://stackoverflow.com/questions/62419827/map-data-using-useref-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!