3 回答

TA貢獻1864條經(jīng)驗 獲得超2個贊
我認為問題是你使用this.setState而不是setGroup
useEffect(() => {
axios.get(config.api.url + '/api/test', options)
.then( (groups) => {
setGroup(groups)
})
.catch( (error) => {
console.log(error);
})
}, [])
改變你的地圖功能
{Object.keys(groups).map( (row, index) => (
<TableRow key={index} selected="false">
<TableCell>{row._id}</TableCell>
<TableCell>{row.user_id}</TableCell>
</TableRow>))}
import '../../App.css';
import React, { useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import config from '../../config/config.json';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
},
heading: {
fontSize: theme.typography.pxToRem(18),
fontWeight: theme.typography.fontWeightBold,
},
content: {
fontSize: theme.typography.pxToRem(14),
fontWeight: theme.typography.fontWeightRegular,
textAlign: "left",
marginTop: theme.spacing.unit*3,
marginLeft: theme.spacing.unit*3,
marginRight: theme.spacing.unit*3
},
table: {
minWidth: 650,
},
tableheader: {
fontWeight: theme.typography.fontWeightBold,
color: "#ffffff",
background: "#3f51b5"
},
tableCell: {
background: "#f50057"
},
button: {
fontSize: "12px",
minWidth: 100
},
}));
export function Main() {
const [groups, setGroup] = React.useState([]);
const classes = useStyles();
const options = {
'headers': {
'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
}
}
useEffect(() => {
axios.get(config.api.url + '/api/test', options)
.then( (groups) => {
setGroup(groups.data.subtask)
console.log(groups.data.subtask);
})
.catch( (error) => {
console.log(error);
})
}, [])
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={12} className={classes.content}>
<TableContainer component={Paper}>
<Table id="split_table" size="small">
<TableHead>
</TableHead>
<TableBody>
{Object.keys(groups).map( (item, index) => (
<TableRow key={index} selected="false">
<TableCell>{item.user_id}</TableCell>
<TableCell>{item.task_name}</TableCell>
</TableRow>))}
</TableBody>
</Table>
</TableContainer>
</Grid>
</Grid>
</div>
)

TA貢獻1860條經(jīng)驗 獲得超9個贊
我認為這是Object.keys(groups).
它不是 React 狀態(tài),所以它不會重新渲染?
您能否嘗試創(chuàng)建一個 groupKey 狀態(tài),然后在組更新時使用 Effect 更新狀態(tài)。
const [groupKey,setGroupKey] = useState([]);
useEffect(() => {
setGroupKey(Object.keys(groups));
},[groups]);
在組件中,使用
{groupKey.map((item, index) => (
<TableRow key={index} selected="false">
<TableCell>{item.user_id}</TableCell>
<TableCell>{item.task_name}</TableCell>
</TableRow>))
}
你明白了。
添加回答
舉報