reactjs 在React中访问axios范围之外的响应数据的方法

j9per5c4  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(115)

这是我第一次开发react应用程序。
我将使用axios的get响应来填充一个表。外部变量在axios的作用域之外声明和使用。
有没有办法在全局范围外/内使用axios的get响应?
非常感谢你的帮助。

const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

let rows = [];

  axios
    .get(`url here`)
    .then(res => {
      console.log(res.data);
     }
    });

  //access res outside scope - is this possible?
  rows.push({res.data});
insrf1ej

insrf1ej1#

您应该使用某种形式的状态来跟踪行。

import React, { useState, useEffect } from "react";
import axios from 'axios';

import "./styles.css";

function App() {
  // Initialize a rows state variable that will be set to [] on the initial load.
  const [rows, setRows] = useState([])

  useEffect(() => {
    // Fetch the data when the component is mounted
    axios
      .get(`url here`)
      .then(res => {
        // Store the response (the rows) in the state variable.
        setRows(res)
      })
  }, [])

  /*
   * On the initial mount nothing will be rendered, when the rows variable
   * is updated a re-render will be triggered and your rows can be rendered.
   */
  return (
    <div>
     { rows.map(row => <tr>A row!</tr>) }
    </div>
  );
}

推荐阅读https://reactjs.org/docs/state-and-lifecycle.html

kgsdhlau

kgsdhlau2#

const getServerData = async ({ filters, sortBy, pageSize, pageIndex }) => {
  await new Promise(resolve => setTimeout(resolve, 500));

  let responseData = {};

  let rows = [];

  axios
    .get(`url here`)
    .then(res => responseData = res.data);

  //access res outside scope - is possible by creating a global variable and assign value to it in the scope.

  rows.push({responseData });
}

相关问题