简体   繁体   中英

React does not wait for the data to be read from the api and returns undefined after run package.json script

I want to create a sitemap by running the package.json script command during build, but it doesn't wait for the data I call from the api and it runs quickly. The data is returned in the log, but it is undefined in the final result.

Package.json

"scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "build:staging": "env-cmd -f ./.env.staging react-scripts sitemap build",
        "sitemap": "babel-node ./src/utils/sitemapBuilder.js"
    },

sitemapBuilder:


import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Generator from 'react-router-sitemap-generator';
import { allPages } from './GetRoutes';

console.log('=>', allPages)  // undefined


const AllRoutes = () => {
  return (
    <Switch>
        <Route path="/" />
        <Route path="/about" />
        <Route path="/contact" />
        <Route path="/blog" />
        {allPages?.map(page => (
          <Route path={page} />
        ))}
    </Switch>
  )
}

AllRoutes();

const generator = new Generator('url', Router(), {
  lastmod: new Date().toISOString().slice(0, 10),
  changefreq: 'monthly',
  priority: 0.8,
});

generator.save('public/sitemap.xml');

GetRoutes:

import React from 'react';
import axios from 'axios';

  let allPages;

  const getAllPages = async () => {
    await axios.get(`url`).then((res) => {
       allPages = res.data.data.map(page => `/${page?.slug}`);
       console.log('allPages: ', allPages) // data return successfully 
      });
    }
  
    getAllPages();

  
  export {
    allPages 
  };
  

I want the final result of a sitemap file to be created in the public folder before the build like this:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>url/</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/about</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/contact</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/blog</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/dynamic-route-1</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/dynamic-route-2</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
<url>
    <loc>url/dynamic-route-3</loc>
    <lastmod>2022-06-04</lastmod>
  </url>
</urlset>

Please guide me

React doesn't care when untracked data changes.

It is seeing that allPages is being exported from GetRoutes.js as a variable with no value. It is mapping over allPages (which is still nothing), and you are getting the result you see.

The only way to see anything once the API request resolves is by storing the data in React state . By storing the data in state , upon it changing it will cause a repaint of the component that is rendering this data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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