我花了几天时间浏览类似的帖子,但没有解决方案。由于某些原因,当我使用setPostState(myState.posts);
时,它不会重新呈现该组件。
我正在使用react ^ 16.10.2
下面是我的代码:
import React,{useState,useCallback} from 'react';
import {withStyles,makeStyles} from '@material-ui/core/styles';
import {Paper,TableRow,TableHead,TableCell,TableBody,Table,Badge,Fab} from '@material-ui/core'
import {myState} from '../../PubSub/pub-sub'
import ThumbUpIcon from '@material-ui/icons/ThumbUp';
import ThumbDownIcon from '@material-ui/icons/ThumbDown';
const StyledTableCell = withStyles(...))(TableCell);
const StyledTableRow = withStyles(...))(TableRow);
const useStyles = makeStyles(theme => (...));
export default props => {
console.log("++++++++++++++++Render Body+++++++++++++++++++++");
const classes = useStyles();
let [postState,setPostState] = useState(myState.posts);// why does setPostState not update badge count???? or re-render component???
let upVote = (id) => {
let objIndex = myState.posts.findIndex((obj => obj.id == id));
return (
<Fab key={"upVote4309lk" +id} color="primary" aria-label="add" classname={classes.fab}
onClick={() => {
myState.posts[objIndex].up_vote++;
setPostState(myState.posts);//why does this not update badge count???? or re-render component???
}}>
<Badge key={"Ubadge"+objIndex} classname={classes.margin} badgeContent={postState[objIndex].up_vote} color="primary"><
ThumbUpIcon> </ThumbUpIcon>
</Badge>
</Fab>
)
};
let downVote = (id) => {
let objIndex = myState.posts.findIndex((obj => obj.id == id));
return (
<Fab key={"downVote0940v" + id} color="primary" aria-label="add" classname={classes.fab}
onClick={() => {
myState.posts[objIndex].down_vote++;
setPostState(myState.posts);//why does this not update badge count???? or re-render component???
}}>
<Badge classname={classes.margin} badgeContent={myState.posts[objIndex].down_vote} color="primary"><
ThumbDownIcon> </ThumbDownIcon>
</Badge>
</Fab>
)
};
function filter(name) {
return name.toLowerCase().includes(props.searchData.title.toLowerCase());
}
function createData(title,description,user,up_votes,down_votes,id) {
if (filter(title,down_votes)) {
return (
<StyledTableRow key={id + "tableKey"}>
<StyledTableCell>{title}</StyledTableCell>
< StyledTableCell>{description}</StyledTableCell>
<StyledTableCell>{user}</StyledTableCell>
<StyledTableCell>{upVote(id)}</StyledTableCell>
<StyledTableCell>{downVote(id)}</StyledTableCell>
</StyledTableRow>
)
}
}
const rows = myState.posts.map(
obj => createData(obj.title,obj.description,obj.user,obj.up_votes,obj.down_votes,obj.id)
);
return (
<Paper classname={classes.root}>
<Table classname={classes.table} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Title</StyledTableCell>
<StyledTableCell>Description</StyledTableCell>
<StyledTableCell>User</StyledTableCell>
<StyledTableCell>Up Votes</StyledTableCell>
<StyledTableCell>Down Votes</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map(row => (row))}
</TableBody>
</Table>
</Paper>
);
}
任何帮助都会很棒,谢谢!