【问题标题】:Fetch data from api in createContext using Fetch api in React doesn't work使用 React 中的 Fetch api 从 createContext 中的 api 获取数据不起作用
【发布时间】:2021-09-29 22:09:21
【问题描述】:

我有一个现有的context 用于产品。最初我使用如下所示的一些模拟数据STORE_DATA 来渲染组件。现在我需要替换该模拟数据并连接到我的local port 上可用的Node.js api(在我创建react-app 之后创建了我的api)。

import React, { createContext, useState } from 'react';
import STORE_DATA from '../shop';

export const ProductsContext = createContext();

const ProductsContextProvider = ({ children }) => {
const [products] = useState(STORE_DATA);

return (
  <ProductsContext.Provider value={{ products }}>
    {
      children
    }
  </ProductsContext.Provider>
 );
}

export default ProductsContextProvider;

刚刚创建了一个helper.js 文件,其中包含以下内容来获取数据:

 import {useEffect} from "react";


const fetchData = () => {
    return fetch("https://localhost:8081/products") <<tested on postman and works fine.
          .then((response) => response.json())
          .then((data) => console.log('Fetching Data:',data));
}

如何替换context 文件上的模拟数据并在context 中使用useEffect 使用此fetchData()?应该改什么代码?

尝试了以下,但没有成功,甚至无法打印console.log

import React, { createContext, useState, useEffect } from 'react';
import { fetchData } from '../helpers';

export const ProductsContext = createContext();

const ProductsContextProvider = ({ children }) => {
  const [products, setProducts] = useState(null);

  useEffect(() => {
    setProducts(fetchData());
    }, []);

  return (
    <ProductsContext.Provider value={{ products }}>
      {
        children
      }
    </ProductsContext.Provider>
  );
}

export default ProductsContextProvider;

【问题讨论】:

    标签: reactjs fetch-api react-context


    【解决方案1】:

    问题在于它返回以下错误 (explained):

    net::ERR_SSL_PROTOCOL_ERROR (on chrome)

    解决方案:在以下代码中的 URL 中使用 http:// 而不是 https://

    const fetchData = () => {
        return fetch("http://localhost:8081/products") 
              .then((response) => response.json())
              .then((data) => console.log('Fetching Data:',data));
    }
    

    【讨论】:

      【解决方案2】:

      CORS 问题。尝试为 CORS 放置标题: 请参阅此链接以获得明确的答案: https://stackabuse.com/handling-cors-with-node-js

      如果没有 CORS 设置,您的 Reactjs API 将被阻止,您可以检查控制台是否相同。 它会抛出:net::ERR_FAILED

      【讨论】:

      • cors 不是问题。它已在api 中使用。问题是如何更改context 代码,它将使用api 而不是模拟数据。
      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多