如何从 axios get() 响应将数据分配给变量
How to assign data to a variable from axios get() response
我正在尝试使用 Express (axios) 构建 React 应用程序。
我能够使用 get() 方法从 MongoDB 获取对象数组。目前该列表被打印到控制台。我怎样才能将它分配给一个变量,以便我可以使用该数组进行进一步的操作?
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => console.log(response.data))
}
expensesListResp();
}, []);
非常感谢!
你可以用下面的方式赋值,假设你有一个数组posts
:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('url')
.then(res => setPosts(res.data))
.catch(err => console.log(err));
}, [])
在你的代码中,你可以这样做:
const [resultArray, setResultArray] = useState([]);
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => setResultArray(response.data))
}
expensesListResp();
}, []);
我假设您在 console.log(response.data)
上打印了数据并且您希望将其分配给一个变量以便您可以正确使用它?
如果是这种情况,您已经在使用 async
函数,只需在 await
.
之前使用您想要的任何变量名称来命名它
for example:
const expensesListResp = async () => {
const "your variable name" = await axios.get('http://localhost:4000/app/expenseslist')
}
如果您想在整个应用程序中使用该变量数据,您还可以将该变量保存在您的状态中。
我正在尝试使用 Express (axios) 构建 React 应用程序。
我能够使用 get() 方法从 MongoDB 获取对象数组。目前该列表被打印到控制台。我怎样才能将它分配给一个变量,以便我可以使用该数组进行进一步的操作?
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => console.log(response.data))
}
expensesListResp();
}, []);
非常感谢!
你可以用下面的方式赋值,假设你有一个数组posts
:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('url')
.then(res => setPosts(res.data))
.catch(err => console.log(err));
}, [])
在你的代码中,你可以这样做:
const [resultArray, setResultArray] = useState([]);
useEffect(() => {
const expensesListResp = async () => {
await axios.get('http://localhost:4000/app/expenseslist')
.then(
response => setResultArray(response.data))
}
expensesListResp();
}, []);
我假设您在 console.log(response.data)
上打印了数据并且您希望将其分配给一个变量以便您可以正确使用它?
如果是这种情况,您已经在使用 async
函数,只需在 await
.
for example:
const expensesListResp = async () => {
const "your variable name" = await axios.get('http://localhost:4000/app/expenseslist')
}
如果您想在整个应用程序中使用该变量数据,您还可以将该变量保存在您的状态中。