获取后我需要使用 h1 删除所有旧 div:
export default function SearchSong() {
const [topSongs, setTopSongs] = useState([]);
let inputEl = useRef(null);
const fetchData = async () => {
更新。这是 fetch(返回正确的数据):
let sTrack = inputEl.current.value;
sTrack = sTrack.replace(/ /g,"+");
try {
const response = await fetch(
`http://ws.audioscrobbler.com/2.0/?method=track.search&track=${sTrack}&api_key=a3c9fd095f275f4139c33345e78741ed&format=json`
);
const data = await response.json();
setTopSongs(data);
} catch (error) {
console.log(error.message);
}
};
return (
<div>
<div className="inner-input">
<div className="container">
<h1 className="search" >Search for song:
</h1>
有输入:
<input ref={inputEl} size="50" type="text"/>
<button class="btn btn-primary" onClick={fetchData} >Fetch</button>
</div>
</div>
{topSongs?.results?.trackmatches?.track.length &&
topSongs.results.trackmatches.track.map((datumn) => {
return (
<div key={datumn.name}>
<h1 className='heading'>{datumn.name}</h1>
</div>
);
})}
</div>
)
}
我试过 useRef 并删除父元素