我找到了一个返回一个词定义的 API。
我想显示一个单词和定义,当按下按钮时,它应该重新获取并显示新单词。
我写了这段代码。但我不能让它工作。我不确定我做错了什么。
我不想使用 Axios 或任何库
import React, { useEffect, useState, Button } from "react";
function RandomWord() {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [refetch, setRefetch] = useState(false);
useEffect(() => {
fetch("https://rnd-word.vercel.app/word")
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [refetch]);
return (
<>
<div class="App">
{isLoading ? (
<p>Loading...</p>
) : (
<span
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) =>
<p>{item.word}</p>
<p>{item.defintion}</p>
}
/>
)}
</div>
<Button
title="New Word"
onPress={() => setRefetch(!refetch)}
color="#e56b6f"
/>
</>
);
}
export default RandomWord;
<span>
reactjs 中的标签只显示普通文本。不像FlatList
在react-native
. 所以你应该使用map
这样的渲染:
{
isLoading ? (
<p>Loading...</p>
) : (
data.map((item, index) => (
<div key={index}>
<p>{item.word}</p>
<p>{item.defintion}</p>
</div>
))
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句