我已經使用 RTK Query 獲取了一些資料。我將這些資料(物件陣列)加載到螢屏中,然后對其進行切片。
這更像是一個打字稿問題,但我會發布 apiSlice:
interface Post {
userId: number;
id: number;
title: string;
body: string;
}
export const blogpostsApi = createApi({
reducerPath: 'blogpostsApi',
baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:3500' }),
endpoints: builder => ({
getBlogPosts: builder.query<Post[], void>({
query: () => '/todos',
transformResponse: (res: Post[], meta) => res.sort((a, b) => b.id - a.id),
}),
}),
});
螢屏上的相關摘錄:
const { data, isLoading } = useGetBlogPostsQuery();
const latestData = data?.slice(0, 10);
useEffect(() => {
if (!isLoading && latestData.length > 0 && some_other_condition) {
... some code
}
}, [latestData]);
useEffect(() => {
if (!isLoading && latestData[0].id === 'something' && some_other_condition) {
... some code
}
}, [latestData]);
如您所見,我已將可選鏈接運算子添加到data?.slice...(因為這是我所看到的 SO 上的推薦解決方案。但是打字稿也強調了latestData.lengthand的所有實體latestData[0].id。
現在我知道我可以通過將可選鏈接運算子添加到所有這些實體來消除打字稿錯誤,但我想知道這真的是最好的方法,原因有兩個:
- 將它添加到所有實體將不必要地增加編譯代碼長度
- 我
latestData在上面的兩個效果中使用的方式是在條件陳述句中檢查它是否存在/是否已定義,因此未定義它是完全可以的。
所以我想我的問題是解決這個錯誤的正確方法是什么。添加可選鏈接運算子是否只是一種快速而骯臟的技巧來消除錯誤,尤其是當它出現在條件陳述句中時?我知道我也可以通過要求 Webstorm 忽略它來抑制錯誤(根據下面的錯誤螢屏截圖)
錯誤:

uj5u.com熱心網友回復:
這是絕對正常的行為。
可選的鏈接運算子不是 Typescript 的東西,它是 Javascript,它的作業方式如下:
myVar?.prop1?.prop2?.prop3
如果myVar是undefined(或null),則不會計算其余代碼,整個運算式將回傳undefined。
然后,如果myVar不是undefined(或null),那么代碼將嘗試訪問 的prop1屬性myVar。
由于有?after prop1,它將重復相同的程序,直到找到undefined/null或到達鏈的末尾而沒有找到任何undefined/ null。
您似乎將 Javascript?運算子與 Typescript!非空斷言混淆了。
如果您只想告訴編譯器您確信變數是“非空”(這也意味著 non undefined),則可以改用!運算子。
像這樣:
const { data, isLoading } = useGetBlogPostsQuery();
const latestData = data!.slice(0, 10); // change this line here
useEffect(() => {
if (!isLoading && latestData.length > 0 && some_other_condition) {
... some code
}
}, [latestData]);
useEffect(() => {
if (!isLoading && latestData[0].id > 0 && some_other_condition) {
... some code
}
}, [latestData]);
但是,如果data不是undefined或null在使用它之前,您真的應該手動檢查。這甚至會讓您不必使用任何斷言運算子!
像那樣:
const { data, isLoading } = useGetBlogPostsQuery();
if (!data){
// do something to handle the problem
}
const latestData = data.slice(0, 10);
useEffect(() => {
if (!isLoading && latestData.length > 0 && some_other_condition) {
... some code
}
}, [latestData]);
useEffect(() => {
if (!isLoading && latestData[0].id > 0 && some_other_condition) {
... some code
}
}, [latestData]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/486064.html
上一篇:期望根減速器是一個函式
