我正在從 API 獲取視頻并且有重復。因此,我應用 uuid 為每個 - 生成一個密鑰,key={uuid()}直到意識到我正在為每個渲染生成一個新密鑰。
下面是我的修復,但我不太確定它是否真的解決了這個問題。
export default function VideoList({ videos, observedElement }) {
const location = useLocation();
const videoList = videos.map((video, index) => {
video.uuid = uuid();
return (
<Link
to={`/videos/${video.id.videoId}`}
state={{ backgroundLocation: location }}
key={video.uuid}
>
<VideoListEntry info={video} ref={observedElement} />
</Link>
);
return <div>{videoList}</div>
}
編輯:我知道使用 db 中的 id 或在給定資料中創建組合更可取。但我只想知道是否有辦法用 uuid 生成穩定的密鑰。
uj5u.com熱心網友回復:
正確的方法是直接從您獲取視頻的任何地方獲取 id。
下一個是在您從遠程位置收到它們的那一刻生成它們(假設您從 API 獲取它們)。所以,在得到它們之后,用 uuid 豐富它們,然后將它們存盤到 state/store。
第三種解決方案是在組件內部使用 a useEffect,它只會在 video 屬性更改時生成 id。
export default function VideoList({
videos = [],
observedElement
}) {
const location = useLocation();
const [videosWithId, setVideosWithId] = useState(videos);
useEffect(() => {
const withId = videos.map(video => ({
...video,
uuid: uuid()
}))
setVideosWithId(withId);
}, [videos]);
// use videosWithId from below this point, instead of the videos prop
....
}
uj5u.com熱心網友回復:
像這樣定義一個保存uuid值的變數并使用它我認為它對你有用
export default function VideoList({ videos, observedElement }) {
const location = useLocation();
const videoList = videos.map((video, index) => {
let uuid = uuid()
video.uuid = uuid
return (
<Link
to={`/videos/${video.id.videoId}`}
state={{ backgroundLocation: location }}
key={uuid}
>
<VideoListEntry info={video} ref={observedElement} />
</Link>
);
return <div>{videoList}</div>
}
uj5u.com熱心網友回復:
export default function VideoList({ videos, observedElement }) {
const location = useLocation();
videos.forEach(video => video.uuid = uuid()); // loop through the list and generate the id
const videoList = videos.map((video, index) => {
return (
<Link
to={`/videos/${video.id.videoId}`}
state={{ backgroundLocation: location }}
key={video.uuid}
>
<VideoListEntry info={video} ref={observedElement} />
</Link>
);
return <div>{videoList}</div>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/457637.html
標籤:javascript 反应
下一篇:按日期排序陣列
