React组件中Get接口重复调用问题解决方案咨询
解决React中useEffect重复调用API的问题
问题描述
开发客户列表页面时,在useEffect中添加Get接口调用后,每次URL获取信息渲染页面时,该Get方法都会被重复调用;移除useEffect及其内部代码后,页面仅加载一次,需要解决这个循环调用的问题。
问题原因
当前的useEffect没有传递依赖数组,这会导致它在**组件每次渲染(包括state更新后)**都执行一次。而你在useEffect内部调用了setCoustomer更新state,触发组件重新渲染,进而再次触发useEffect,形成了无限循环。
解决方案
给useEffect添加空的依赖数组[],这样useEffect只会在组件首次挂载时执行一次,不会因为state更新或组件重新渲染而重复触发。
同时可以优化代码中的几个细节:
- 修正
useState的拼写错误(setCoustomer→setCustomers) - 用
map替代forEach处理接口返回数据(forEach不支持异步,await在这里无效) - 避免在组件内部声明可复用的临时数组,直接在接口回调中处理数据
修正后的完整代码
import { useEffect, useState } from "react"; // 补充导入useState import { api } from "../../../api.js"; import './list.css'; function CustomerList() { const [customers, setCustomers] = useState([]); // 修正拼写错误 useEffect(() => { console.log('get data from server'); api.get('/Customer', { auth: { username: 'user', password: 'pass' } }).then(function (response) { // 用map处理数据,替代forEach+push const customerList = response.data.map(element => ({ Id: element.id, CustomerName: element.customerName, CustomerCode: element.customerCode, Tel: element.tel, Mobile: element.mobile, Connector: element.connector, AddDate: element.addDate, })); setCustomers(customerList); }).catch(error => { console.log("response received: %s ", error); alert(error.response?.data?.erro || '请求出错'); // 添加可选链避免报错 console.log("Error received: %s ", error.response?.data?.erro); }); }, []); // 添加空依赖数组 console.log('read'); return ( <> <div className="container"> <div className="row align-items-start"> <h1 className="listTitle">لیست مشتری ها</h1> </div> <div className="row align-items-start"> <div className="table-responsive"> <table className="table table-striped table-hover"> <thead className="table-dark"> <tr> <th scope="col">#</th> <th scope="col">Customer Name</th> <th scope="col">Customer Code</th> <th scope="col">ُTel</th> <th scope="col">Mobile</th> <th scope="col">CC</th> </tr> </thead> <tbody> {customers.map((o) => ( <tr key={o.Id}> <th scope="row">{o.Id}</th> <td>{o.CustomerName}</td> <td>{o.CustomerCode}</td> <td>{o.Tel}</td> <td>{o.Mobile}</td> <td>{o.Connector}</td> </tr> ))} </tbody> </table> </div> </div> </div> {console.log('read end')} </> ); } export default CustomerList;
API定义(无需修改)
import axios from 'axios' export const api = axios.create({ baseURL : 'https://******.com/aorBackend/aor.dll' });
内容的提问来源于stack exchange,提问作者GBg
相关产品推荐
相关产品推荐

