【问题标题】:Way to access response data outside the scope of axios in React在 React 中访问 axios 范围之外的响应数据的方法
【发布时间】:2019-05-21 10:59:47
【问题描述】:

这是我第一次开发 React 应用程序。

我将使用 axios 的 get 响应来填充表格。外部 var 在 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});

【问题讨论】:

    标签: javascript reactjs axios


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

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

      让 responseData = {};

      让行 = [];

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

      //访问范围外的资源 - 可以通过创建一个全局变量并在范围内为其赋值。

      rows.push({responseData });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-10-07
        • 1970-01-01
        • 1970-01-01
        • 2021-12-04
        • 2022-01-27
        • 1970-01-01
        • 2022-11-21
        相关资源
        最近更新 更多