[英]I cannot map on the data fetched from API
我使用 Redux-Saga 從 API 獲取數據,但是當它更新 state 時我無法使用它。 這可能是因為我試圖在數據加載到 redux state 之前訪問數據。
//saga.js
import axios from 'axios';
import { put, takeLatest, all } from 'redux-saga/effects'
const URL = "https://api.staging.gamerarena.com/disputes/";
function* fetchInfo() {
const res = yield axios.get(URL).then((response) => response);
yield put({
type: 'FETCH_INFO',
payload: res
})
}
function* actionWatcher() {
yield takeLatest('GET_INFO', fetchInfo)
}
export default function* rootSaga() {
yield all([
actionWatcher(),
]);
}
上面,您可以看到 GET_INFO 觸發了 fetch_info,但它會在所有其他操作之后更新 state。 我試圖用 useEffect 修復它,但它沒有幫助,或者我沒有正確使用它。
const DisputeCard = (props) => {
const state = useSelector(state => state?.apiInfo?.apiInfo[0]?.results)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInfo()) ;
console.log("State is ", state) // state returns undefined in the console
}, [] );
是的,您無法在獲取數據之前訪問數據。 您可以等待數據獲取或將回調 function 傳遞給您的操作。
使用另一個 useEffect 來等待獲取數據,您可能還必須等待數據在組件內呈現。
const state = useSelector(state => state?.apiInfo?.apiInfo[0]?.results)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getInfo()) ;
}, [] );
useEffect(() => {
if(state) {
console.log("State is ", state);
}
}, [state] );
if(!state) {
return null;
}
return (
<div>{state}</div>
)
或將回調傳遞給您的操作:
export const getInfo = createAction("GET_INFO", (callback) => {
return callback;
})
function* fetchInfo(action) {
const callback = action.payload;
const res = yield axios.get(URL).then((response) => response);
callback(res)
yield put({
type: 'FETCH_INFO',
payload: res
})
useEffect(() => {
dispatch(
getInfo((res) => {
console.log("State is ", state)
})) ;
}, [] );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.