导出在 React 组件的 fetch() 函数内的 then() 方法内创建的变量

Export a variable created inside a then() method within a fetch() function for a React Component

我需要从头开始总结我的问题:

我正在创建一个带有反应框架的结构来构建一个简单的反应页面。我想我可以将其定义为单页应用程序:

结构如下:

现在我的文章-content.js文件有以下代码:

import $ from "jquery";
const rootURL = 'mytargetwebsite';

const config = {
    rootURL: rootURL,
    taskRoute: `${rootURL}/wp-json/wp/v2/posts`,
};


let articles = '';
let the_request = $.ajax({
    type: 'GET',
    url: config.taskRoute,
    async: false,
});

the_request.done(function(data){

    articles = data.map(data => (

    {
        name: data.title.rendered,
        title: data.link,
        excerpt: data.excerpt.rendered,
        content: data.content.rendered
    }

    ));

});
export default articles;

它工作正常,但理想情况下,这不是我想要 运行 我的应用程序的方式,因为我的目标是使用承诺或提取 API 导出变量并重用它在另一个文件中,如下所示:

ArticlesList.js:

import React from 'react';
import { Link } from 'react-router-dom';

const ArticlesList = ({ articles }) => (
    <>
    {articles.map((article, key) => (
        <Link className="article-list-item" key={key} to={`/article/${article.name}`}>
            <h3>{article.title}</h3>
            <h3>{article.name}</h3>
            {/*<div>{article.content}</div>*/}
            <div
            dangerouslySetInnerHTML={{
                __html: article.content
            }}></div>
        </Link>
    ))}
    </>
);

export default ArticlesList;

所以,我尝试使用 fetch API 几次,但无法导出它,因为当我尝试 运行 [=57] 上的 .map 函数时=] 页面会抛出一个错误。

类似于:

const ciao = async () => { 
    function fetchDemo() {
        return fetch(config.taskRoute).then(function(response) {
            return response.json();
        }).then(function(json) {
            let articles = json.map(data => (
            {
                name: data.title.rendered,
                title: data.link,
                content: data.content.rendered
            }
            ));
            return articles;

        });
    }
}
const articles = ciao();
console.log(articles);

由于某种原因永远不会奏效,但另一方面,这个想法会奏效,因此文章将记录一个承诺,它已解决并包含我需要映射或循环的数据另一页。

promise 的方法非常相似,并且与其他情况一样,将起作用:

const articles = new Promise((resolve,reject) => {
    fetch(config.taskRoute, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json', },
    })
    .then(response => response.json())
    .then(data => {
        resolve(data.map(data => ({
            name: data.title.rendered,
            title: data.link,
            content: data.content.rendered
        })));
    })
    .catch((error) => {
        reject(error)
    });
});

export default articles;

但是,我仍然无法导出我的变量,因为它会在另一个文件 (ArticlesList.js) 中失败。

我尝试了其他几种方法,但到目前为止都失败了。

有什么提示吗?

更新:

一定有什么我不知道的,因为理论上我的代码可以正常工作:

ArticlesList.js

import React from 'react';
import { Link } from 'react-router-dom';
import articles from "../pages/article-content";

articles.then(articles => {
    console.log(articles);
    return;

});

如果我 console.log 文章,它包含我需要映射的值,但是一旦我尝试映射它们:

console.log(articles);//works!
const ArticlesList = ({ articles }) => (
    <>
    {articles.map((article, key) => (
        <Link className="article-list-item" key={key} to={`/article/${article.name}`}>
            <h3>{article.title}</h3>
            <h3>{article.name}</h3>
            {/*<div>{article.content}</div>*/}
            <div
            dangerouslySetInnerHTML={{
                __html: article.content
            }}></div>
        </Link>
    ))}
    </>
);//doesn't work

我会得到一个:

TypeError: articles.map is not a function

而不是尝试导出 articles(由于很多原因这是不可能的)为什么不简单地导出一个用文章解决的承诺?

const rootURL = 'mywebsite';

const config = {
    rootURL: rootURL,
    taskRoute: `${rootURL}/wp-json/wp/v2/posts`,
}

const articles = new Promise((resolve,reject) => {
    fetch(config.taskRoute, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json', },
    })
    .then(response => response.json())
    .then(data => {
        resolve(data.map(data => ({
            name: data.title.rendered,
            title: data.link,
            content: data.content.rendered
        })));
    })
    .catch((error) => {
        reject(error)
    });
});

export default articles;

在导入文件中

import articles from "./articles";

articles.then(articlesArray => {
    // Here articlesArray is an array and it must be used in this function
});

// Here aritclesArray is not defined

请注意,此方法仅在您需要在启动时加载文章时有效,如果您稍后需要在您的应用程序中再次加载文章,最好导出一个 return Promise 函数而不是导出承诺自己。

您应该导出一个获取文章的函数,而不是导出文章,然后处理所有异步等待或承诺解析您在

中使用该函数的相应组件中的函数
const rootURL = 'mywebsite.xyz/';

const config = {
    rootURL: rootURL,
    taskRoute: `${rootURL}/wp-json/wp/v2/posts`,
};

const getPeopleInSpace = () => 
    return fetch(config.taskRoute) 
       .then(res => res.json());

const getArticles = () => 
    getPeopleInSpace()
    .then(json => {
        const article = json.map(data => {
            return {
            name: data.title.rendered,
                title: data.link,
                content: data.content.rendered
            }
        });
        return article;
    })

export default getArticles ;

现在您可以在任何组件中使用上述功能,例如

import getArticles from 'path/to/getArticles';

class App extends React.Component {
   ...
   componentDidMount() {
       getArticles().then(articles => {
          console.log(articles);
          // set articles in state and use them
       }) 
   }
}

你不应该导出从 API 中获取的文章的一个原因是因为每次你导入文件时,都会有一个新的请求,但是当请求完成并且你的项目是可供使用。通过导出函数,您可以处理成功和错误情况