简体   繁体   English

如何使用带有 useEffect 钩子的 react fetch() 和 map 获取的数据

[英]how to use react fetch() with useEffect hook and map the fetched data

Trying to fetch api data on frontend using useEffect hook,尝试使用 useEffect 挂钩在前端获取 api 数据,

i am able console log the data but unable to map it somehow我能够控制台记录数据,但无法以某种方式 map

new to react新反应

console output控制台 output

function SlugBook() {
    // let {slug} = useParams(),
    const [state, setState] = useState([])
    
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{CSRF_TOKEN....}
            )
            .then(response => response.json()) 
            .then(data => console.log(data)) -->works fine
            .then(data => setState(data)); --> not sure
        
           })

         return (
               <p>
            {state.map( d => (<li>{d}</li>))} ---> error code ()
               </p>
            )
            }
 export default SlugBook

Two problems:两个问题:

  1. You need to set your state inside the second then like so:你需要在第二个里面设置你的 state then像这样:
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{
            credentials: 'include',
            method: 'GET',
            mode: 'same-origin',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'X-CSRFToken': CSRF_TOKEN
            }})
            .then(response => response.json()) 
            .then(data => setState(data))
    })
  1. You need to use a dependency array in your useRef or else you will get infinite re-renders.您需要在useRef中使用依赖数组,否则您将获得无限的重新渲染。 So change it to:所以改成:
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{
            credentials: 'include',
            method: 'GET',
            mode: 'same-origin',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'X-CSRFToken': CSRF_TOKEN
            }})
            .then(response => response.json()) 
            .then(data => console.log(data)) -->works fine
            .then(data => setState(data)); --> not sure

        
    }, [])

Setting the dependancy array to an empty array [] will ensure that your useEffect only runs your fetch once on first render.将依赖数组设置为空数组[]将确保您的useEffect仅在第一次渲染时运行一次fetch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM