【发布时间】:2021-01-24 20:28:00
【问题描述】:
我正在使用 React useState() 和 useEffect 从 api (mock-data/my-data.json) 获取多个数据。
我想从 api 中获取 Category Title 和 Posts 列表并在 jsx 中呈现它们。
这是使用useState() 和useEffect() 获取数据的正确方法吗?我创建了多个 useState 常量,因此在我可以在渲染方法中渲染 Title 和列表操作 Posts 之后:
function ArticleList() {
const [categoryTitle, setCategoryTitle] = useState('')
const [posts, setPosts] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(true)
axios
.get('mock-data/my-data.json')
.then(res => {
console.log(res.data)
setCategoryTitle(res.data['title'])
setPosts(res.data.allItems)
setLoading(false)
})
.catch(err => {
console.log(err)
})
}, [])
if (loading) {
return <p>Loading articles...</p>
}
return (
<div>
<h1>{categoryTitle}</h1>
<ul>
{posts.map(post => (
<li key={post.id}>{post.titel}</li>
))}
</ul>
</div>
)
}
【问题讨论】:
-
您可以使用多个
useStates 和useEffects。你有什么错误吗? -
这对我来说看起来不错。
-
它的概念是对的,但避免直接从组件调用API,最好创建一个分离的可重用操作和服务。
标签: reactjs axios use-effect use-state