我正在将我的React编写为功能组件。我想执行提取并等待渲染完成。但是fetch总是发送未处理的Promise,并且呈现时记录为null。如何使其成为同步过程?
export default function SimpleTable() {
const classes = useStyles();
let records = null;
fetch(socket+'get_all_records')
.then(response => response.json())
.then(json => {records = json.record});
return (
<Paper className={classes.root}>
<Table className={classes.table} aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell align="right">DoorId</TableCell>
<TableCell align="right">Time</TableCell>
<TableCell align="right">Permission</TableCell>
<TableCell align="right">Image</TableCell>
</TableRow>
</TableHead>
<TableBody>
{records.map(record => (
<TableRow key={record.UserID}>
<TableCell component="th" scope="row">{record.UserID}</TableCell>
<TableCell align="right">{record.DoorID}</TableCell>
<TableCell align="right">{record.Time}</TableCell>
<TableCell align="right">{record.AccessGranted}</TableCell>
{/*<TableCell align="right">{record.ImageID}</TableCell>*/}
<TableCell>
<img src={socket+'get_image?image_id='+record.ImageID} height="42" width="42"/>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
}
答案 0 :(得分:1)
首先,records
必须是一种状态,否则重新分配它(then(json => {records = json.record})
)不会触发重新渲染。
您可以使用conditional rendering根据records
的值来决定您的组件呈现什么:
export default function SimpleTable() {
const [records,setRecords] = useState(null);
useEffect(() => {
fetch(socket+'get_all_records')
.then(response => response.json())
.then(response => {setRecords(response)});
}, []);
return (
!response ? <Loading /> : (
<Paper className={classes.root}>...</Paper>
)
)
}