首页 > 解决方案 > 条件渲染显示两个组件

问题描述

我有两个要根据状态条件渲染的组件,但我遇到了一个问题,即在显示正确组件之前的一瞬间显示了错误的组件。

异步获取数据:

  const [test, setTest] = useState();
  const [loading, setLoading] = useState();
  const [error, setError] = useState(); 

  const fetchData = async () => {
    console.log("running");
    setLoading(true);
    setError(false);
    try {
      const result = await axios(
        "https://jsonplaceholder.typicode.com/posts/props.selectedId" // Is dynamic and changes on user click
      );
      setTest(result.data);
    } catch (error) {
      if (error.response.status == 404) {
        setError(error);
        setTest(null);
      }
    }
    setLoading(false);
  };

渲染:

  return (
    <div className={classes.root}>
      {!loading && !error && test? (
        <div>
          <Card className={classes.card}>
            <CardContent>
              <Title>Adattributes</Title>
              <Typography variant="h6" component="h1">
                name
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={3}>
                  <Typography variant="subtitle2" component="h1">
                    address
                  </Typography>
                  {test.title}
                </Grid>
              </Grid>
            </CardContent>
            <CardActions>
              <Component1
                value={test}
                setTest={setTest}
              />
            </CardActions>
          </Card>
        </div>
      ) : (
        <Component2 setTest={setTest} />
      )}
    </div>
  );
});

我在条件渲染上做错了吗?还是与获取异步有关?

标签: javascriptreactjs

解决方案


在第一行中,您使用没有初始状态的useState钩子,因此您的状态变为未定义(请记住,未定义是假值)。

const [test, setTest] = useState();

您应该为test设置初始状态,或者更改渲染组件的条件。


推荐阅读