![](/img/trans.png)
[英]How to map an API with Typescript in ReactJS?
[英]How to solve ReactJs (typescript) mapping issue, map() not working
我正在嘗試使用 ReactJs 中的 map (使用 TypeScript)從項目列表中更新項目。 但是找不到問題。
const [orderList, setOrderList] = useState([])
...
setOrderList( orderList.map( order:any => {
if( order.id == orderId)
return {...order, review_id:1}
return order
}))
顯示以下 typescript 提示:
Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
Type 'any[]' is not assignable to type 'never[]'.
Type 'any' is not assignable to type 'never'.ts(2345)
提前致謝
首先,將正確類型的數組傳遞給useState
以便它返回正確類型的 state 和設置器 function
const [orderList, setOrderList] = useState([] as Order[]);
這是必要的,因為表達式[]
的推斷類型是因為在這種情況下沒有 TypeScript 可以推斷的上下文。 在這種情況下,我使用了類型斷言,但還有其他方法( useState<Order[]>([])
)。
其次,永遠不要在內聯回調參數上放置類型注釋。 這是一種可怕的編碼模式,它隱藏了錯誤並且完全沒有意義,因為類型推斷確保了安全性和正確的類型傳播。
setOrderList(orderList.map(order => {
if (order.id === orderId)
return {...order, review_id: 1};
return order;
}));
筆記:
正如其他人所指出的,如果您有一個一元箭頭 function 需要對其參數進行類型注釋,那么您必須用括號將參數列表括起來。 例如
const processOrder = (o: Order) => {...};
在上面,我們只用類型注釋o
,因為語言沒有推理上下文來推斷其類型。
嘗試使用const [orderList, setOrderList] = useState<any[]>([])
。
順便說一句,我不知道你是否注意到,但使用 typescript 的想法是避免使用any
.
只需在map回調中使用括號()
orderList.map((order:any) => {
if(order.id === orderId) {
return {...order, review_id:1}
}
return order
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.