React中如何将接口返回的JSON数据填充到useState定义的lineItems状态
实现方案
你可以通过两种方式完成字段映射和状态更新,核心逻辑是对接口返回的items子数组做遍历映射,把接口字段对应到lineItems的属性上:
方案1:直接在fetch请求成功后处理(推荐,性能更好)
直接修改你现有getItems方法里的响应处理逻辑,拿到接口数据后直接映射生成目标结构,同时更新lineItems状态:
const getItems= () => { fetch(`${process.env.REACT_APP_API_URL}/invoice/Draft/1`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'x-business-name' : 'billings', "Accept":"application/json" }, }) .then(response => response.json()) .then(res => { // 保留原items状态的更新 setItems(res) // 校验数据存在后做字段映射 if (res.length && res[0]?.items) { const mappedLineItems = res[0].items.map(rawItem => ({ // 接口返回的item字段对应lineItems的name属性,若实际字段有出入可自行调整 name: rawItem.item, description: rawItem.description, quantity: rawItem.quantity, price: rawItem.price })) // 覆盖更新lineItems状态 setLineItems(mappedLineItems) } }) .catch(err => console.log(err)) }
方案2:监听items状态变化更新
如果你需要保留现有items状态的更新逻辑,也可以单独加一个副作用监听items的变化,自动同步更新lineItems:
useEffect(() => { if (items.length && items[0]?.items) { const mappedLineItems = items[0].items.map(rawItem => ({ name: rawItem.item, description: rawItem.description, quantity: rawItem.quantity, price: rawItem.price })) setLineItems(mappedLineItems) } // 依赖项为items,items变化时自动触发映射更新 }, [items])
字段映射说明
接口返回的子项字段和lineItems属性对应关系如下,你可以根据实际接口返回调整:
- 接口
rawItem.item→lineItems.name - 接口
rawItem.description→lineItems.description - 接口
rawItem.quantity→lineItems.quantity - 接口
rawItem.price→lineItems.price
内容的提问来源于stack exchange,提问作者kaskousGaming
相关产品推荐
相关产品推荐

