【问题标题】:React Context API, Data loading twice. Once with the data and the other withoutReact Context API,数据加载两次。一次有数据,一次没有
【发布时间】:2020-08-05 23:47:19
【问题描述】:

这是我为正在编写的简单程序创建上下文的方式

import React, { useState, createContext, useEffect } from "react";

export const PhotoContext = createContext();

export const PhotoProvider = (props) => {
  const [photo, setPhoto] = useState([]);

  useEffect(() => {
    console.log("Use Effect Runs  HAHAHAH");
    console.log("HAHAHAHAHAHAHAH");
    fetchPhotos();

    async function fetchPhotos() {
      const url =
        "https://raw.githubusercontent.com/bobziroll/scrimba-react-bootcamp-images/master/images.json";

  

      fetch(url)
        .then((res) => res.json())
        .then((arr) => {
          setPhoto(arr);
        })
        .catch(console.log("ERROR"));
    }
  }, []);

  return (
    <PhotoContext.Provider value={[photo, setPhoto]}>
      {props.children}
    </PhotoContext.Provider>
  );
};

还有另一个文件,我想在其中加载照片变量中的数据。这是它的代码。我已经使用 setTimeout 来查看问题到底出在哪里。似乎每当 setTimeout 中的语句运行时,控制台中的值都会返回两次。首先,它是空的,第二个是实际值。但是从那以后,我尝试访问 photos.url,并且由于第一次未定义,程序崩溃了。

import React, { useState, useContext } from "react";
import { PhotoContext } from "../Context/PhotoContext";

const Photos = (props) => {
  const [photos, values] = useContext(PhotoContext);

  setTimeout(() => {
    console.log(photos[0].url);
  }, 3000);
  return <div>{}</div>;
};

export default Photos;

非常感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs react-native react-hooks react-context


    【解决方案1】:

    没有发现问题。我为您的示例创建了沙箱。 https://codesandbox.io/s/inspiring-lovelace-5r1gb?file=/src/App.js

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 2020-06-04
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      相关资源
      最近更新 更多