React点击Fetch按钮新增地址Div而非替换内容的问题求助
解决每次点击Fetch按钮新增地址卡片的问题
你的核心问题是当前状态仅存储单个地址对象,每次获取新数据都会覆盖旧值。要实现新增效果,需要把状态改成数组来存储所有地址,每次获取新数据时往数组里追加元素。
以下是修改后的完整代码:
import { useState, Fragment } from 'react'; import axios from 'axios'; const AddressFetcher = () => { // 把状态改成数组,存储所有地址 const [addressList, setAddressList] = useState([]); const [loading, setLoading] = useState(false); const fetchapi = async () => { try { setLoading(true); const response = await axios.get("https://random-data-api.com/api/v2/addresses"); // 用扩展运算符追加新地址到数组,不覆盖旧数据 setAddressList(prevList => [...prevList, response.data]); console.log(response.data); } catch (error) { console.log(error); } finally { // 无论成功失败都要把loading设回false setLoading(false); } }; // 根据索引删除对应的地址 const removeElement = (index) => { setAddressList(prevList => prevList.filter((_, i) => i !== index)); }; return ( <Fragment> <div> <button onClick={fetchapi} disabled={loading}> {loading ? 'Fetching...' : 'Fetch Location'} </button> {/* 遍历地址数组,渲染每个地址卡片 */} {addressList.map((address, index) => ( <div key={address.id || index} // 优先用接口返回的唯一id,无id时用索引兜底 style={{ backgroundColor: "#c7c7c7", display: "flex", flexDirection: "column", padding: 16, margin: 5, borderRadius: 20 }} > <p><strong>Address: {address.street_address}</strong></p> <p><strong>City: {address.city}</strong></p> <p><strong>Street Name: {address.street_name}</strong></p> <p><strong>Zipcode: {address.zip_code}</strong></p> <button onClick={() => removeElement(index)}>remove</button> </div> ))} </div> </Fragment> ); }; export default AddressFetcher;
关键修改点:
- 状态结构调整:将单个对象状态改为数组,用来存储所有获取到的地址。
- 状态更新逻辑:使用函数式更新状态,基于旧数组创建新数组并追加新地址,避免直接修改原数组。
- 删除逻辑适配:删除函数接收索引参数,通过
filter方法过滤掉对应元素,实现单个卡片删除。 - 交互体验优化:添加
finally块确保loading状态重置,给按钮加disabled属性防止重复点击。
内容的提问来源于stack exchange,提问作者Luis Colon
相关产品推荐
相关产品推荐

