反应-UseState不会在useEffect钩子内部获取后触发重新渲染

时间:2020-04-23 12:07:07

标签: reactjs react-hooks

我正在使用挂钩完成我的第一个React教程-我正在尝试在useEffect中获取本地数据,然后使用useState更新状态。然后,我将状态传递给子元素(Card.js)所预订的Context.provider。即使useEffect运行,Card组件和状态也不会重新呈现/更新。我在做什么错了?

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-

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

1 个答案:

答案 0 :(得分:0)

您的useEffect数组中没有任何依赖项。这就是为什么在安装应用后它不会再次触发的原因。您需要向其传递一个依赖项,以便每次依赖项值更改时它都可以再次运行。另外,请考虑在loadData函数之前添加异步。