我試圖避免具有值為“{}”的物件串列
import { IRootState } from 'app/shared/reducers';
import { getEntity } from './determination.reducer';
import { IDetermination } from 'app/shared/model/tpa/determination.model';
import React, { lazy, useEffect } from 'react';
import { connect } from 'react-redux';
import { Link, RouteComponentProps } from 'react-router-dom';
export interface IDeterminationDetailProps extends StateProps, DispatchProps, RouteComponentProps<{ id: string }> {}
export const DeterminationDetail = (props: IDeterminationDetailProps) => {
useEffect(() => {
props.getEntity(props.match.params.id);
}, []);
function waitForElementProps(){
if(props != null && props){
console.log('finished loading props.. ' props.determinationEntity)
} else {
setTimeout(waitForElementProps, 5000);
}
}
waitForElementProps();
var {determinationEntity} = props;
const obj = JSON.stringify(determinationEntity);
if(obj === '{}') {
console.log('caught')
waitForElementProps();
}
if(!obj || obj==null || obj ==='{}'){
waitForElementProps();
}
waitForElementProps();
console.log('new ' obj);
在控制臺輸出中我得到
finished loading props.. [object Object]
caught
finished loading props.. [object Object]
new {}
determination/FETCH_DETERMINATION_FULFILLED
finished loading props.. [object Object] 2
new {"determination":{"id":1051,"a ... }
即使我在遞回函式到達那里之前呼叫了遞回函式,我的代碼如何可能將“{}”的值分配給“obj”?
這個問題與我希望在決議資料之前等待資料到達有關,因為每當我嘗試決議它時,我都會遇到“obj is undefined”的問題。
我知道javascript中有異步等待,我可以等待'FETCH_DETERMINATION_FULFILLED'完成,但我不知道如何實作它。這是我的 api 呼叫(來自一個單獨的類)
export const getEntities: ICrudGetAllAction<IDetermination> = (page, size, sort) => {
const requestUrl = `${apiUrl}${sort ? `?page=${page}&size=${size}&sort=${sort}` : ''}`;
return {
type: ACTION_TYPES.FETCH_DETERMINATION_LIST,
payload: axios.get<IDetermination>(`${requestUrl}${sort ? '&' : '?'}cacheBuster=${new Date().getTime()}`),
};
};
uj5u.com熱心網友回復:
簡而言之,
- async/await 是理想的答案,但是
- 添加空檢查,和
- 使用 setTimeout 不是執行緒阻塞
異步/等待
理想情況下,您將在您實作的 useEffect 掛鉤中等待來自 API 的回應。這意味著代碼將等待 API 回應,然后再移動到 useEffect 掛鉤的下一行。然后,您可以將回應中的值保存在狀態物件中以供以后使用。這可能看起來像這樣簡單:
useEffect(() => {
const getData = async () => {
const res = await props.getEntity(props.match.params.id);
const resData = await res.json();
// now save to state
setData(resData);
// or parse as you need (as example)
setName(resData?.details?.name);
}
getData();
}, []);
添加空值檢查
從您提供的代碼中,很難判斷這些值是如何從當前的 API 保存到props.determinationEntity變數中的。但是,無論此更新如何發生,您都應該在稍后在代碼中使用該值時應用檢查,以免出現型別錯誤。使用可選鏈接、無效合并和簡單if(!props.determinationEntity) return;陳述句。
setTimeout 不是執行緒阻塞的
關于你說的:
即使我在遞回函式到達那里之前呼叫了遞回函式,我的代碼如何可能將“{}”的值分配給“obj”?
在 waitForElementProps 函式內呼叫 setTimeout 不會阻止所有代碼繼續。超時將被保存,代碼執行將繼續通過堆疊,到達宣告obj并將其設定為空物件的字串。
var同樣的原因也要小心。它將宣告提升為函式范圍而不是塊范圍,例如letand const,因此您可以在“不應該”的地方訪問變數(取決于您的期望)。
uj5u.com熱心網友回復:
React(和 Javascript)本質上是異步的。無法阻止等待異步操作完成。即使 async/await 實際上也不會阻塞,它只是.then.
處理此問題的反應方式是強制父組件始終傳遞您想要的道具,或者null在未填充道具時進行渲染,以便在加載資料之前不會向 DOM 渲染任何內容。像這樣:
if (!props.determinationEntity) {
return null;
}
其他一些注意事項:
props 引數不可能為空。如果沒有傳遞任何 props,則 React 傳遞一個空物件。
if (props != null && props)是多余的,在 JavaScript 中 null 是錯誤的,所以這相當于if (props)
uj5u.com熱心網友回復:
利用
使用布局效果
useLayouteffect(() => {
waitForElementProps(); }, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459491.html
標籤:javascript 反应 json 打字稿
