【问题标题】:useState updates but changes doesnt showuseState 更新但未显示更改
【发布时间】:2021-07-25 01:08:21
【问题描述】:
import React,{useState, useEffect, useRef} from 'react';
import { makeStyles } from '@material-ui/core/styles';

import PostCard from './PostCard'

const useStyles = makeStyles((theme) => ({
    CardContainer: {
      display: "block"
    },
  }));

export default function CardContainer() {
    const classes = useStyles();
    const [posts, setPosts] = useState([]);
  
    useEffect(()=>{
      fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(res => setPosts(res))
      },[])

    console.log(posts)

return (<div className={classes.CardContainer} >
      {!posts.length ? <h1>Loading</h1> : 
      posts.map((post) => {
        <PostCard postInfo={post}/>
      })}
  </div>
  );
}

使用此代码,我看不到 PostCard 组件。 在控制台中首先写入一个空数组,然后来自 fetch 的响应 所以它正确获取但不重新返回?

【问题讨论】:

    标签: reactjs react-hooks fetch use-effect use-state


    【解决方案1】:

    你没有从你的 .map 函数返回任何东西:

    posts.map((post) => {
      <PostCard postInfo={post}/>
    })}
    

    要么使用明确的return

    posts.map((post) => {
      return <PostCard postInfo={post}/>;
    })}
    

    或者去掉函数体:

    posts.map((post) =>
      <PostCard postInfo={post}/>
    )}
    

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多