我有一個計數器,我可以在其中遞減和遞增計數器。我還有一個包含如下專案的陣列:
const gitHubRepos = [
'repo0',
'repo1',
'repo2',
'repo3',
]
我需要使用計數器作為上述陣列的索引(repo0如果計數器為 0,repo1如果為 1,...)并從 GitHub 的 API: 獲取有關 GitHub 存盤庫的資訊https://api.github.com/repos/{repoName}。但是如何將計數器與陣列連接起來,同時獲取特定倉庫的資訊?
uj5u.com熱心網友回復:
您可以根據您的 counter 使用 useEffect 來獲取。例如:
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [counter, setCounter] = useState(0)
const gitHubRepos = [
'repo0',
'repo1',
'repo2',
'repo3',
]
useEffect(()=>{
console.log(`${gitHubRepos[counter]}`)
fetch(`https://api.github.com/repos/${gitHubRepos[counter]}`);
},[counter])
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={()=>setCounter(counter 1)}>increment</button>
</div>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/427152.html
