我有 JSON 結果,一次只需要按 id 回傳四個結果。使用按鈕,點擊后,我必須只顯示接下來的四個,重復,直到 JSON 資料集結束。我不關心處理到達資料集末尾后會發生什么,盡管如果有解決方案,我也很聽話。
function App() {
const [data, setData] = useState([])
const [count, setCount] = useState(4)
// MY QUESTION IS HERE
const next4 = () => setCount(count 4)
const API = "http://localhost:3001/sushis";
const x = () => {
fetch(API)
.then(r => r.json())
.then(k => setData(k))
}
useEffect(() => {
x()
}, [])
return (
<div className="app">
<SushiContainer data={data}
count={count}
next4={next4} />
<Table />
</div>
);
}
import React from "react";
import MoreButton from "./MoreButton";
import Sushi from "./Sushi"
// import { v4 } from "u uid"
function SushiContainer({ data, count, next4 }) {
return (
<div className="belt">
{data.slice(0, count).map(d => {
return ( <Sushi key={d.id}
name={d.name}
img={d.img_url}
price={d.price}
created={d.created_at} /> )
})}
<MoreButton next4={next4} />
</div>
);
}
export default SushiContainer;
在頁面加載時,我會看到前四個結果。問題來了,當單擊一個按鈕只回傳接下來的四個時。我在按鈕上設定了一個回呼,并且使用上面我突出顯示的代碼,回呼叫于將接下來的四個結果添加到前四個,總共八個,這不是我想要的。
[
{
"id": 1,
"name": "Maguro Magic",
"img_url": "./sushi/maguro.png",
"price": 20,
"created_at": "2018-07-27T18:53:16.241Z"
},
{
"id": 2,
"name": "Tsundere Ebi",
"img_url": "./sushi/ebi.png",
"price": 15,
"created_at": "2018-07-27T18:53:16.244Z"
},
{
"id": 3,
"name": "Oh Sake",
"img_url": "./sushi/sake.png",
"price": 10,
"created_at": "2018-07-27T18:53:16.248Z"
},
{
"id": 4,
"name": "Kawaii Tobiko",
"img_url": "./sushi/tobiko.png",
"price": 25,
"created_at": "2018-07-27T18:53:16.251Z"
},
{
"id": 5,
"name": "Tsundere Ebi",
"img_url": "./sushi/ebi.png",
"price": 15,
"created_at": "2018-07-27T18:53:16.255Z"
},
{
"id": 6,
"name": "Oh Sake",
"img_url": "./sushi/sake.png",
"price": 10,
"created_at": "2018-07-27T18:53:16.258Z"
},
{
"id": 7,
"name": "Kawaii Tobiko",
"img_url": "./sushi/tobiko.png",
"price": 25,
"created_at": "2018-07-27T18:53:16.260Z"
},
{
"id": 8,
"name": "Tsundere Ebi",
"img_url": "./sushi/ebi.png",
"price": 15,
"created_at": "2018-07-27T18:53:16.264Z"
},
}
我只需要顯示 data.id 1-4,然后只顯示 5-8,然后只顯示 9-12,依此類推。
uj5u.com熱心網友回復:
看起來您正在處理未在此處添加的 SushiContainer 中要顯示的專案。這取決于 SushiContainer 中發生的事情,但您應該一次只能將 4 個資料項傳遞給它來解決您的問題
<SushiContainer
data={data.slice(count-4, count)}
next4={next4}
/>
注意:這將在每次渲染時創建一個新的串列參考,并會導致 SushiContainer 重新渲染,因此最好在傳遞串列之前記住該串列
const currentData = useMemo(() => {
return data.slice(count-4, count)
}, [data, count])
...
<SushiContainer
data={currentData}
next4={next4}
/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397744.html
上一篇:如何使用松露框架為硬幣設定圖示
下一篇:使用dict格式化JSON
