问题
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