My code is here.
I expect the content of the array testingData
should be shown.
However, it does not be shown.
When I remove the useEffect
hook, it works.
Would you tell me why and how can I fix it?
Advertisement
Answer
In react, a component only renders if there are any state or prop changes. In your codebase rowList
is a variable instead of a state. if you convert it to state, it should work.
import React, { useContext, useEffect, useState } from "react"; import WebContext from "./WebContext"; export default function QQTableBody(props) { let { testingData, setTestingData } = useContext(WebContext); const [rowList, setRowList] = useState([]); // let rowList=[]; useEffect(() => { const list = []; testingData.forEach(data => { list.push( <tr> <td>{data}</td> </tr> ); }); setRowList(list); }, [testingData]); return <tbody>{rowList}</tbody>; }