这是我第一次开发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});
答案 0 :(得分:0)
const getServerData =异步({过滤器,sortBy,pageSize,pageIndex})=> { 等待新的Promise(resolve => setTimeout(resolve,500));
let responseData = {};
让行= [];
axios
.get(url here
)
.then(res => responseData = res.data);
//访问范围以外的资源-通过创建全局变量并在范围内为其分配值,可以实现该操作。
rows.push({responseData});
答案 1 :(得分:0)
您应该使用某种形式的状态来跟踪行。
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>
);
}