React AJAX - REACT教程

React AJAX

在 React 应用中实现 AJAX 请求,通常可以使用 fetch API 或者第三方库如 axios、jquery 等库来进行网络请求。

以下是使用这两种方法的基本说明:

使用 fetch API 进行 AJAX 请求

fetch 是一个在浏览器中内置的 API,用于发起网络请求。以下是使用 fetch 在 React 组件中发起 AJAX 请求的基本步骤:

  • 引入 fetch - 如果你使用的是现代浏览器,通常不需要引入 fetch 。但是,如果你需要支持旧浏览器,可以使用 unfetch 这样的 polyfill。

  • 使用 useEffect 钩子 - 利用 useEffect 钩子来处理副作用,比如发起网络请求。

  • 发起请求 - 使用 fetch 发起 GET 或 POST 请求。

  • 处理响应 - 使用 .then() 来处理响应数据。

  • 错误处理 - 使用 .catch() 来捕获并处理错误。

  • 更新状态 - 使用 useState 钩子来存储请求的数据,并在请求成功后更新状态。

示例代码
importReact,{useState,useEffect}from'react';constMyComponent=()=>{const[data,setData]=useState(null);const[loading,setLoading]=useState(true);useEffect(()=>{constfetchData=async()=>{try{constresponse=await fetch('https://api.example.com/data');constresult=await response.json();setData(result);setLoading(false);}catch(error){console.error('Error fetching data:',error);}};fetchData();},[]);if(loading){return<div>Loading...</div>;}return(<div><h1>Data from API:</h1><pre>{JSON.stringify(data,null,2)}</pre></div>);};exportdefaultMyComponent;

说明:

  • useState 和 useEffect :使用 useState 来存储 AJAX 请求返回的数据 ( data ) 和加载状态 ( loading ),并使用 useEffect 在组件加载后执行 AJAX 请求。

  • fetch :使用 fetch 发起 GET 请求,并使用 response.json() 将返回的 JSON 数据解析为 JavaScript 对象。

  • 异步处理 :使用 async/await 来处理异步操作,确保在请求完成后更新状态。

  • 错误处理 :在 fetch 请求中使用 try/catch 来捕获和处理可能发生的错误。

使用 axios

axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 Node.js。

以下是使用 axios 的基本步骤:

  1. 安装 axios - 通过 npm 或 yarn 安装 axios。

    
    npm install axios
    
    
  2. 引入 axios - 在组件中引入 axios。

  3. 发起请求 - 使用 axios 发起 GET 或 POST 请求。

  4. 处理响应和错误 - 使用 .then() .catch() 来处理响应和捕获错误。

  5. 更新状态 - 与使用 fetch 类似,使用 useState 更新状态。

示例代码
importReact,{useState,useEffect}from'react';importaxios from'axios';constMyComponent=()=>{const[data,setData]=useState(null);const[loading,setLoading]=useState(true);useEffect(()=>{constfetchData=async()=>{try{constresponse=await axios.get('https://api.example.com/data');setData(response.data);setLoading(false);}catch(error){console.error('Error fetching data:',error);}};fetchData();},[]);if(loading){return<div>Loading...</div>;}return(<div><h1>Data from API:</h1><pre>{JSON.stringify(data,null,2)}</pre></div>);};exportdefaultMyComponent;

使用 jQuery 在线测试

以下实例演示了获取 Github 用户最新 gist 共享描述:

React 组件的数据可以通过 componentDidMount 方法中的 Ajax 来获取,当从服务端获取数据时可以将数据存储在 state 中,再用 this.setState 方法重新渲染 UI。

当使用异步加载数据时,在组件卸载前使用 componentWillUnmount 来取消未完成的请求。

示例代码
classUserGistextendsReact.Component{constructor(props){super(props);this.state={username:'',lastGistUrl:''};}componentDidMount(){this.serverRequest= $.get(this.props.source,function(result){varlastGist=result[0];this.setState({username:lastGist.owner.login,lastGistUrl:lastGist.html_url});}.bind(this));}componentWillUnmount(){this.serverRequest.abort();}render(){return(<div>{this.state.username}用户最新的Gist共享地址:<ahref={this.state.lastGistUrl}>{this.state.lastGistUrl}</a></div>);}}constroot=ReactDOM.createRoot(document.getElementById("root"));root.render(<UserGistsource="https://api.github.com/users/octocat/gists"/>);

以上代码使用 jQuery 完成 Ajax 请求。