React Component渲染两次


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

const RECIPES_URL = ''
export default function App() {
  const classes = useStyles();
  const [data, setData] = useState({});

    useEffect(() => {
            .then(res => {
            .catch(err => {
    }, []);
  return (
    <div className={classes.root}>
      <RecipeList recipes={data}/>


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.