Reactjs 如何将后端API与react应用程序集成
我正在创建一个react应用程序,我有一个现成的API,但我不知道如何集成它。您可以通过对API进行网络调用来集成后端Reactjs 如何将后端API与react应用程序集成,reactjs,Reactjs,我正在创建一个react应用程序,我有一个现成的API,但我不知道如何集成它。您可以通过对API进行网络调用来集成后端 // Step 1 - import the necessary packages import React, {useState, useEffect} from 'react' import axios from 'axios' const App = () => { // Step 2 - declare useState hook with inital dat
// Step 1 - import the necessary packages
import React, {useState, useEffect} from 'react'
import axios from 'axios'
const App = () => {
// Step 2 - declare useState hook with inital data as a empty array
const [data, setData] = useState([]);
// Step 3 - Make a asynchronus call to fetch the data from api
const fetchDataFromApi = async () => {
const response = await axios.get(`https://yourapi.com/data`);
setData(response.data);
}
// Step 4 - call the fetchDataFromApi function indide useEffect so that its called when componeent is mounted
useEffect(() => {
fetchDataFromApi();
}, []);
// Step 5 - Map the data inside your markup
return (
<div>
{data && data.map(items =>
<div key={items.id}>{items.name}</div>
)}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
//步骤1-导入必要的包
从“React”导入React,{useState,useEffect}
从“axios”导入axios
常量应用=()=>{
//步骤2-将初始数据为空数组的useState挂钩声明
const[data,setData]=useState([]);
//步骤3-进行异步调用以从api获取数据
const fetchDataFromApi=async()=>{
const response=等待axios.get(`https://yourapi.com/data`);
setData(response.data);
}
//步骤4-调用fetchDataFromApi函数indide useEffect,以便在装入componeent时调用它
useffect(()=>{
fetchDataFromApi();
}, []);
//步骤5-映射标记中的数据
返回(
{data&&data.map(项=>
{items.name}
)}
);
}
ReactDOM.render(,document.getElementById('root'))
不要忘了在react组件中运行命令npm i axios来安装axios,在需要API数据的地方,可以实现API调用的方法,例如
updateData(){}
,然后调用componentDidMount()
和/或componentDidUpdate()
class MyComponent extends React.Component {
componentDidMount() {
this.updateData();
}
componentDidUpdate(prevProps) {
// Do something with the props and call
this.updateData();
// if needed
}
updateData() {
let api_url = ''; // dynamic url - depends on the state?
fetch(api_url, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(result => {
// Do something with the API data
// this.setState({ data } )
})
.catch(error => {
// handle the error appropriately
});
}
}