【问题标题】:React - api call returns undefinedsReact - api调用返回未定义
【发布时间】:2021-06-19 12:10:26
【问题描述】:

const [loading, setLoading] = useState(false);
  const [meal, setMeal] = useState([]);

  useEffect(() => {
    setLoading(true);
    async function fetchData() {
      const response = await axios.get('/random.php');
      setMeal(response.data.meals);
      setLoading(false);
      return response;
    }

    fetchData();
  }, []);

  return (
    <Card className={classes.Root}>
      <CardActionArea>
        <CardMedia className={classes.Media} title="food">
          <img src={meal[0].strMealThumb} alt="cat" />
        </CardMedia>
        <CardContent>
          <Typography gutterBottom variant="h5" component="h2">
            {meal[0].strMeal}
          </Typography>
          <Typography variant="body2" color="textSecondary" component="p">
            {meal[0].strInstructions}
          </Typography>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <Button size="small" color="primary">
          Learn More
        </Button>
      </CardActions>
    </Card>
  );

我正在使用上面的 coed,但出现错误 TypeError: Cannot read property 'strMealThumb' of undefined。我用 useEffect 尝试了多种方法,但仍然遇到同样的问题

【问题讨论】:

    标签: axios react-hooks use-effect


    【解决方案1】:

    当你的组件第一次渲染时,对/random.php的网络请求还没有发生,所以meal被设置为它的默认值([])。您尝试将图像源设置为meal[0].strMealThumb,但meal 是一个空数组,因此meal[0] 返回undefined,您会看到您发布的错误。

    解决方案是防止组件主体在meal 正在加载时,以及当meal 为空数组时(以防/random.php 返回空数组)。

    meal 是一个数组,因此您应该将其命名为 meals

    const MyComponent = () => {
      const [loading, setLoading] = useState(false);
      const [meals, setMeals] = useState([]);
    
      if (loading) {
        return (
          <div>Loading...</div>
        );
      }
    
      if (meals.length === 0) {
        return (
          <div>No meals found!</div>
        );
      }
    
      return ( /* ... */ );
    };
    

    【讨论】:

    • 它起作用了,我按照建议重命名为吃饭。谢谢:D
    猜你喜欢
    • 2020-05-06
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多