我有一种需要在React函数组件中调用API的场景。如果可能的话,如何返回结果。我可以调用API,但是响应在变量中可用。请指教
我的示例代码
import React from 'react';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import axios from 'axios';
const Table = (props) => {
const getData = [axios.get("https://lq-time-
tracking.firebaseio.com/user.json").then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
})]
const data = [{getData}];
const columns = [{
id: 'Name',
Header: 'Name',
accessor: data.user
}, {
Header: 'Date',
accessor: 'Date',
}, {
Header: 'Comment',
accessor:'Comment'
}]
return <ReactTable
data={...data}
columns={columns}
pivotBy={ ['Date', 'Name']}
/>
}
export default Table;
答案 0 :(得分:2)
您可能要使用几个钩子; useEffect
执行API查询,useState
存储数据。 useEffect
挂钩中的空依赖项数组将确保仅在安装组件时才进行API调用。然后,当呼叫解决后,数据将设置为名为data
的有状态变量。
import React, { useEffect, useState } from 'react';
import ReactTable from 'react-table'
import 'react-table/react-table.css'
import axios from 'axios';
const Table = (props) => {
const [data, setData] = useState({});
useEffect(() => {
axios.get("https://lq-time-tracking.firebaseio.com/user.json")
.then(function(response) {
setData(response.data);
}).catch(function(error) {
console.log(error);
})
}, []);
const columns = [{
id: 'Name',
Header: 'Name',
accessor: data.user
}, {
Header: 'Date',
accessor: 'Date',
}, {
Header: 'Comment',
accessor:'Comment'
}]
return <ReactTable
data={...data}
columns={columns}
pivotBy={ ['Date', 'Name']}
/>
}
export default Table;
答案 1 :(得分:0)
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}