我想在標簽中顯示我的資料值,每次都必須使用 .map 嗎?
資料庫呼叫:
const { carId } = useParams();
const { carType, setCarType } = useState([]);
const getCar (carId) => {
CarTypes.GetCar(carId)
.then(response) => {
setCarType(response.data.data);
}
}
return {
<h2 className="title"> { carType.CarMake } </h2>
}
有沒有不同的方法來做到這一點?我沒有收到錯誤訊息,但是我是否需要執行 .map 來獲取值?它只回傳一個值。
我是否需要每次都這樣做,回應中只有 1 個值?
{ carType.map(data => (
<h2 className="title"> { carType.CarMake } </h2>
)}
uj5u.com熱心網友回復:
如果您真的確定陣列中總會有一個元素,您可以使用如下陣列定義來分配它。
const { carId } = useParams();
const [carType, setCarType] = useState([]);
const getCar (carId) => {
CarTypes.GetCar(carId).then({data}) => {
// See array definition like in the useState
const [singleCar] = data.data;
setCarType(singleCar);
}
}
return {
<h2 className="title"> { carType.CarMake } </h2>
}
你可以這樣使用它而不使用 map()
uj5u.com熱心網友回復:
我認為這是因為,在第一次渲染中,您的狀態“carType”為空,因此它無法找到“CarMake”,因此請嘗試以下操作:
{!!carType.length &&
<h2 className="title"> { carType.CarMake } </h2>
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369624.html
上一篇:當我單擊類組件ReactJS中的按鈕時,我希望影像發生變化
下一篇:將反應路由器轉換為v6
