如何在React中展示SQL COUNT查询请求返回的客户总数值
实现步骤
1. 声明响应式状态存储总数
首先需要在React组件内引入useState Hook,声明专门的状态来存储接口返回的客户总数,初始值可以设为0,也可以设为null用来做加载态判断:
// 组件顶部先引入依赖 import { useState, useEffect } from 'react'; import axios from 'axios'; // 组件内部开头声明状态 const [clientCount, setClientCount] = useState(0);
2. 修改接口请求逻辑,把返回值存入状态
你当前代码里的setClients()没有传入任何值,需要改成把接口返回的total_client传入状态更新函数:
const getCountClients = () => { axios.get("http://localhost:4000/api/v1/clients/count-client") .then((res) => { // 把接口返回的总数存入状态 setClientCount(res.data.total_client); console.log(res.data); }) .catch(error => { console.log(error); }) }; useEffect(() => { getCountClients(); },[]);
3. 替换硬编码数值,渲染状态
把原来写死的2换成你声明的状态变量即可,注意JSX语法中使用变量需要用大括号包裹:
<div className="featuredItem"> <span className="featuredTitle">Effectifs totals</span> <div className="featuredNumberContainer"> <span className="featuredNumber">{clientCount}</span> <span className="featuredNameInfo">Clients</span> </div> </div>
可选优化(加载状态)
可以新增加载状态,避免接口请求过程中显示初始值0不符合业务预期:
// 新增加载状态 const [loading, setLoading] = useState(true); const getCountClients = () => { setLoading(true); axios.get("http://localhost:4000/api/v1/clients/count-client") .then((res) => { setClientCount(res.data.total_client); }) .catch(error => { console.log(error); }) .finally(() => setLoading(false)) }; // 渲染时做状态判断 <span className="featuredNumber">{loading ? '加载中...' : clientCount}</span>
内容的提问来源于stack exchange,提问作者max
相关产品推荐
相关产品推荐

