React前端如何展示接口返回的对象数组中指定id对应元素的内容
实现步骤
首先你现有代码的useEffect没有配置空依赖数组,会导致组件每次渲染都重复发起接口请求,先修复这个问题,再通过前端数组过滤即可实现需求:
方案1:前端直接过滤现有数据(无需修改后端,适合当前小数据量场景)
修改后的App.js完整代码如下:
import Axios from 'axios'; import React, {useState, useEffect} from "react"; const App = () => { const [signalList, setsignalList] = useState([]); useEffect(()=> { Axios.get("http://localhost:3001/api/get").then((response) => { console.log("response data: "); console.log(response.data); setsignalList(response.data) }) }, []) // 加空依赖数组,只在组件挂载时请求一次 // 查找id为1的对象,注意如果你的id是字符串类型,要把1改成'1' const targetItem = signalList.find(item => item.id === 1) return ( <div> <h1>Show me Text from object with id 1</h1> {/* 有匹配数据时才渲染,避免接口返回前报错 */} {targetItem && <p>{targetItem.text}</p>} {/* 注意:上面的text要替换成你数据库表里存储文本的实际字段名,可从控制台打印的返回数据里确认字段名 */} </div> ); } export default App;
方案2:后端新增单条查询接口(性能更优,适合数据量大的场景)
- 后端
index.js新增接口代码:
// 原有代码保留,新增以下接口 app.get('/api/getById/:id', (req,res)=>{ const { id } = req.params; // 用参数占位符避免SQL注入 const sqlSelect = 'SELECT * FROM myDatabase.signaldb WHERE id = ?'; db.query(sqlSelect, [id], (err,result)=> { if (err) console.log(err); res.send(result[0] || {}); }) })
- 前端
App.js修改为单独请求该接口:
import Axios from 'axios'; import React, {useState, useEffect} from "react"; const App = () => { const [targetItem, setTargetItem] = useState({}); useEffect(()=> { Axios.get("http://localhost:3001/api/getById/1").then((response) => { console.log("target data: ", response.data); setTargetItem(response.data) }) }, []) return ( <div> <h1>Show me Text from object with id 1</h1> {targetItem?.text && <p>{targetItem.text}</p>} </div> ); } export default App;
内容的提问来源于stack exchange,提问作者Liebertosan
相关产品推荐
相关产品推荐

