简体   繁体   English

我不能对从 API 获取的数据进行 map

[英]I cannot map on the data fetched from API

I fetch data from an API with Redux-Saga but I cannot use it when it updates state.我使用 Redux-Saga 从 API 获取数据,但是当它更新 state 时我无法使用它。 It is probably because I am trying to access the data before it is loaded to the redux 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(),
  ]);
}

Above, you can see that GET_INFO triggers fetch_info, but it updates the state after all other actions.上面,您可以看到 GET_INFO 触发了 fetch_info,但它会在所有其他操作之后更新 state。 I tried to fix it with useEffect but it did not help or I have not used it properly.我试图用 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

    }, [] );

包含已定义错误的控制台

Yes you can not access the data before its get fetched.是的,您无法在获取数据之前访问数据。 Either you can wait for the data to get fetched or pass a callback function to your action.您可以等待数据获取或将回调 function 传递给您的操作。

Use an0ther useEffect to wait for the data to get fetched, also you might have to wait for the data to render inside your component.使用另一个 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>
)

Or pass a callback to your action:或将回调传递给您的操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM