React项目中如何将Fetch获取的数据转为JSX渲染
实现选中宝可梦数据的渲染
要把选中的宝可梦数据渲染到JSX里,按以下步骤修改即可:
- 新增状态存储选中的宝可梦详情
在组件中添加一个useState,用来保存选中后的宝可梦完整数据:
const [selectedPokemon, setSelectedPokemon] = useState(null);
- 修改Downshift的onChange逻辑
把原来打印数据的代码替换成更新状态的操作:
onChange={selection => fetch(`http://localhost:3001/search/${selection.value}`) .then(res => res.json()) .then(data => setSelectedPokemon(data)) }
- 在JSX中渲染数据
在Downshift组件之后添加渲染区域,根据selectedPokemon是否存在展示内容。注意stats是数组类型,需要遍历才能正常显示具体状态:
{selectedPokemon && ( <div> <p>pokemon name {selectedPokemon.name}</p> <div> pokemon stats: <ul> {selectedPokemon.stats.map((stat, idx) => ( <li key={idx}>{stat.stat.name}: {stat.base_stat}</li> ))} </ul> </div> </div> )}
修改后的完整代码
import React, { useState, useEffect } from 'react'; import Downshift from 'downshift' export default function TestSearchBar() { const [pokemonData, setPokemonData] = useState(null); // 新增状态存储选中的宝可梦详情 const [selectedPokemon, setSelectedPokemon] = useState(null); useEffect(() => { Pokemons(); async function Pokemons() { const res = await fetch(`http://localhost:3001/pokemon/names`); const data = await res.json(); setPokemonData(data); } }, []); const items = pokemonData; return ( <div> <Downshift onChange={selection => fetch(`http://localhost:3001/search/${selection.value}`) .then(res => res.json()) .then(data => setSelectedPokemon(data)) // 更新状态代替打印 } itemToString={item => (item ? item.value : '')} > {({ getInputProps, getItemProps, getLabelProps, getMenuProps, isOpen, inputValue, highlightedIndex, selectedItem, getRootProps }) => ( <div> <label {...getLabelProps()}>Enter a pokemon </label> <div style={{ display: 'inline-block' }} {...getRootProps({}, { suppressRefError: true })}> <input {...getInputProps()} /> </div> <ul {...getMenuProps()}> {/* 处理初始加载时items为null的情况 */} {isOpen && items ? items.filter(item => !inputValue || item.value.includes(inputValue)).map((item, index) => ( <li {...getItemProps({ key: item.value, index, item, style: { backgroundColor: highlightedIndex === index ? 'lightgray' : 'white', fontWeight: selectedItem === item ? 'bold' : 'normal' } })}> {item.value} </li> )) : null} </ul> </div> )} </Downshift> {/* 渲染选中的宝可梦数据 */} {selectedPokemon && ( <div> <p>pokemon name {selectedPokemon.name}</p> <div> pokemon stats: <ul> {selectedPokemon.stats.map((stat, idx) => ( <li key={idx}>{stat.stat.name}: {stat.base_stat}</li> ))} </ul> </div> </div> )} </div> ); }
额外说明
- 初始加载时
pokemonData为null,所以渲染下拉列表时要加上&& items判断,避免触发空值报错 stats是数组,不能直接通过{selectedPokemon.stats}输出,必须遍历每个状态项展示具体内容
内容的提问来源于stack exchange,提问作者snippy
相关产品推荐
相关产品推荐

