【发布时间】:2021-08-22 23:27:47
【问题描述】:
我正在构建我的第一个 React 应用程序,但遇到了问题。
我想创建一个简单的应用程序,我可以在其中单击侧边栏中的书名,并查看该书的摘要。我通过我在本地定义的 API 获取书名和摘要。
现在,点击书名没有任何作用。我在控制台中收到红色错误:
index.js:1 Warning: Each child in a list should have a unique "key" prop.
我这样调用我的 API:
const [viewingId, setViewingId] = useState()
const [bookList, setBookList] = useState([])
const [contents, setContents] = useState({})
useEffect(() => {
fetch("http://localhost:5000/books")
.then(res => res.json())
.then(res => {setBookList(res)})
}, [])
const fetchBookSummary = (id) => {
fetch(`http://localhost:5000/book/${id}`)
.then(res => res.json())
.then(res => {
setContents({...contents, [id]: res[0]})
})
}
这就是我定义“onClick”函数的方式:
const seeSummary = (id) => {
fetchBookSummary(id)
setViewingId(id)
}
最后,我的 App 呈现如下:
return (
<div className="App">
<div className="App-Container">
<div className="BookList">
{bookList.map(book => (
<Node book={book} onClick={() => seeSummary(book.id)} />
))}
</div>
<div className="SummaryView">
{contents[viewingId]?.content?.map((summaryData => (
<Summary summaryData={summaryData}/>
)))}
</div>
</div>
</div>
);
}
我以前只有onClick={seeSummary(book.id)},但出现“重新渲染过多”错误...我不确定我是否理解添加() => 的作用。
我希望在单击一本书时能够看到摘要。任何帮助表示赞赏!
【问题讨论】: