【问题标题】:React component not rendering on state updateReact 组件未在状态更新时呈现
【发布时间】:2021-12-21 07:15:31
【问题描述】:

我正在从我的 API 加载一些数据,它已成功返回,但 React 之后没有渲染卡片。

export default function Subjects() {
  const userApi = useUserService();
  const auth = useRecoilValue(AuthAtom);
  const [loading, setLoading] = React.useState<boolean>(true);
  const [subjects, setSubjects] = React.useState<Subject[]>();

  React.useEffect(() => {
    userApi.getSubjects(auth?.userId ?? 0).then((value: Subject[]) => {
      setSubjects(value);
      setLoading(false);
    });
  }, []);

  return (
    <Box display="flex" flexDirection="row" alignItems="center">
      {!loading &&
        subjects?.map(function (subject: Subject) {
          <Card key={subject.name}>
            <CardActionArea>
              <CardContent>{subject.name}</CardContent>
            </CardActionArea>
          </Card>;
        })}
    </Box>
  );
}

userApi.getSubjects 返回一个主题数组。

【问题讨论】:

  • thisthis
  • @T.J.Crowder 谢谢,我现在明白我的错误了!!

标签: reactjs typescript react-hooks material-ui


【解决方案1】:

您不会在 .map 回调中返回任何内容,因此您的组件不会呈现任何内容。修复它:

subjects?.map(function (subject: Subject) {
  // add the return statement like below.
  return (
    <Card key={subject.name}>
      <CardActionArea>
        <CardContent>{subject.name}</CardContent>
      </CardActionArea>
    </Card>
  );
})}

【讨论】:

    【解决方案2】:

    您在正文中的函数不返回任何内容。试试这个:

    return (
        <Box display="flex" flexDirection="row" alignItems="center">
          {!loading &&
            subjects?.map(function (subject: Subject) {
              return (
                 <Card key={subject.name}>
                   <CardActionArea>
                     <CardContent>{subject.name}</CardContent>
                   </CardActionArea>
                 </Card>;
              );
            })}
        </Box>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 2018-09-21
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多