![](/img/trans.png)
[英]What is the right way to toggle a value inside object state in React hooks?
[英]React TypeScript right way to set select value and state
我正在嘗試在我的 React 項目中學習使用 TypeScript。
我為傳入的數據格式(名稱和網址)做了一個類型。
type PokedexType = {
name: string;
url: string;
}
從API返回的數據是一個對象數組(帶有名稱和 url)。
{
"results": [
{
"name": "national",
"url": "https://pokeapi.co/api/v2/pokedex/1/"
},
{
"name": "kanto",
"url": "https://pokeapi.co/api/v2/pokedex/2/"
},
// ...
];
}
在我的useEffect()
中,我將這些對象存儲在帶有setState()
的 state 中。
useEffect(() => {
api.get('/pokedex')
.then((response) => {
setPokedex(response.data.results);
})
.catch((error) => {
console.log(error);
});
});
因為 API 返回一個數組,所以我對設置useState()
的正確方法感到困惑。
// this works
const [pokedex, setPokedex] = useState<Array<PokedexType>>([{ name: "", url: "" }]);
// these also work
const [pokedex, setPokedex] = useState<PokedexType>({ name: "", url: "" });
const [pokedex, setPokedex] = useState<Array<PokedexType>>();
const [pokedex, setPokedex] = useState(); // (with checking)
我知道指定類型是為了類型檢查,但是如果 state 立即被覆蓋,這有關系嗎?
我正在嘗試將狀態名稱( i
.name)設置為我的 select 的值,正確的方法是什么? 由於 state 現在是一個數組,我如何將值設置為相應的屬性(像這樣)?
<select value={pokedex.name}>
你不能只說pokedex.name
。 pokedex
是一個數組,因此您必須遍歷該數組。 例如
//just a mock, will come from your ajax request const pokedex = [ { "name": "national", "url": "https://pokeapi.co/api/v2/pokedex/1/" }, { "name": "kanto", "url": "https://pokeapi.co/api/v2/pokedex/2/" } ] const Select = () => ( <select > {pokedex.map(el => < option value = {el.name} >{el.name}</option>)} </select>) // Render it ReactDOM.render( < Select / >, document.getElementById("react") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="react"></div>
還要看一下接口:
interface IPokedex {
name: string;
url: string;
}
const [pokedex, setPokedex] = useState<IPokedex[]>([{ name: "", url: "" }]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.