我正在尝试将数据从父组件传递到呈现表格的子组件。第一次一切正常,但如果我按下刷新,孩子将不再看到数据。非常感谢任何关于如何让孩子每次都能看到数据的帮助。下面是我的代码。谢谢:
const Parent = () => {
const [data, setData] = useState([])
const getData = async(req, res)=>{
try{
const res = await axios.get(url to data);
const data = await res.data
setData(data) //<---this works fine
}catch(error){
console.log(error)
}
}
useEffect(()=>{
getData()
},[])
return(
<div style={pageStyle}>
<Child data={data}/> //<---this sends ok the first time
</div>
)
}
export default Parent
Child Component:
const child = (props) => {
const [data, setData] = useState(props.data || []) //<--first time ok, no data after refresh
const [fields, setFields] = useState([])
const getheaders=(req, res)=>{
let fieldList = []
Object.keys(data[0]).map((field, index)=>(
fieldList.push({field: field}) //<--This works the first time but breaks after because the there is no data
))
setFields(fieldList)
}
useEffect(()=>{
getheaders() //<--works fine on first load, not on refreshes because data is missing
},[])
return (
<div className="ag-theme-quartz" style={{ height: "100%" }}>
<AgGridReact rowData={data} columnDefs={fields} />
</div>
)
}
export default Child
当 prop 改变时,useState 钩子不会自动更新状态。 你可以看看我对以下问题的回答: