React Component渲染两次

我不知道为什么,第一个渲染显示一个空对象,第二个渲染显示我的数据:

function RecipeList(props) {
    return (
        <div>
            {console.log(props.recipes)}
            {/*{props.recipes.hits.map(r => (*/}
            {/*    <Recipe initial="lb" title={r.recipe.label} date={'1 Hour Ago'}/>*/}
        </div>
    )
}

const RECIPES_URL = 'http://cors-anywhere.herokuapp.com/http://test-es.edamam.com/search?i?app_id=426&q=chicken&to=10'
export default function App() {
  const classes = useStyles();
  const [data, setData] = useState({});

    useEffect(() => {
        axios.get(RECIPES_URL)
            .then(res => {
                setData(res.data);
            })
            .catch(err => {
                console.log(err)
            })
    }, []);
  return (
    <div className={classes.root}>
      <NavBar/>
      <RecipeList recipes={data}/>
      <Footer/>
    </div>
  );
}

我不知道为什么,我在这里苦苦挣扎了一个多小时(React新手),所以我一定很想念东西。

enter image description here

评论
  • Lee
    Lee 回复

    This is perfectly normal, React will render your component first with no data. Then when your axios.get returns and update data, it will be rendered again with the new data

  • 薄荷情
    薄荷情 回复

    This is the expected behavior. The reason you see two console logs is because, the first time RecipeList is called with no data (empty object), and the second time when the data becomes available. If you would like to render it only when the data is available you could do something like {Object.keys(data).length > 0 && <RecipeList recipes={data}}. Btw this is called conditional rendering.