简体   繁体   English

React - UseState 在 useEffect 钩子中获取后未触发重新渲染

[英]React - UseState not triggering rerender following fetch inside useEffect hook

I am just working through my first React tutorial using hooks - I am using trying to fetch local data within useEffect and then update the state using useState.我正在使用钩子完成我的第一个 React 教程 - 我正在尝试在 useEffect 中获取本地数据,然后使用 useState 更新 state。 I am then passing the state into a Context.provider which a child element (Card.js) subscribes to.然后,我将 state 传递到子元素(Card.js)订阅的 Context.provider 中。 Even though useEffect runs, the Card component and the state isn't being rerendered/updated.即使 useEffect 运行,卡组件和 state 也不会重新渲染/更新。 What am I doing wrong?我究竟做错了什么?

MainContext.js - MainContext.js -

import React, { createContext, useState, useContext, useEffect, Fragment } from 'react';


import List from '../containers/List';

export const myContext= createContext();


export const MainContext = ({children}) => {

  const [films, setFilms] = useState([]);

  const loadData = () => {
    try {
      fetch('../src/assets/data.json').then( result => result.json()).then(movies => { 
      setFilms(films)      
      }) 
    } catch (error) {
      console.log('there has been an error')
    }}


  useEffect(() => { 

    loadData() 

    },[]);


   return (

      <myContext.Provider value={{films,setFilms }}>
        {children()}
      </myContext.Provider>
    );

  } 

Card.js - Card.js -

function Card() {

  const {films} = useContext(myContext)

  if (films !== undefined) { 
    return (

      <div>
        { films.map((movie,i) => {
          return (
          <div key={i}>
            <img src={movie.img.src} className='card-img-top' alt={movie.img.alt} />
          <div className='card-body'>
            <h2 className='card-title'>{`#${movie.ranking} - ${movie.title} (${movie.year})`}</h2>
          </div>
          <ul className='list-group list-group-flush'>
            <li className='list-group-item'>{`Distributor: ${movie.distributor}`}</li>
            <li className='list-group-item'>{`Amount: ${movie.amount}`}</li>
          </ul></div>
          )
        })

        }
      </div>
    )
  } else {
  return <div>{'Update Failed'}</div>
  }

}

export default Card

You don't have any dependency in your useEffect array.您的 useEffect 数组中没有任何依赖项。 This is why it doesn't trigger again once the app is mounted.这就是为什么应用程序安装后它不会再次触发的原因。 You need to pass it a dependency, so it can run again each time the dependency value changes.您需要向它传递一个依赖项,以便每次依赖项值更改时它都可以再次运行。 Also, consider adding async before your loadData function.此外,请考虑在您的 loadData function 之前添加异步。

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

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