首页 > 解决方案 > 我的 reactJS 组件中的 React-redux 状态未定义错误

问题描述

这是我的初始状态:

 export const initialState = {
  currencieList: [],
  currentPage: 1,
  pageCount: 1,
  itemsPerPage: 20,
};

这是我想要触发动作的 redux-saga:

  function* loadDataAsync() {
  console.log("SAGAS WORKS");
  yield delay(5000);
  try {
    const {body: data} = yield call(agent.get, "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=xxx");
    getCurrencies({currencies : data.data});
    console.log('--------getCurrencies', getCurrencies);
    setPageCount();
    yield put({type:"LOAD_DATA_ASYNC"});
  } catch (err) {
    console.log(err)
    yield put({type:"LOAD_DATA_ASYNC_ERROR"})
  }
}

export function* watchLoadDataAsync() {
  yield takeLatest("LOAD_DATA", loadDataAsync);
}

Getcurrencies减速器:

 export const getCurrencies = (currencies) => {
  return {
    type: actionTypes.LOAD_DATA_ASYNC,
    payload : currencies,
  };
};



 case actionTypes.LOAD_DATA_ASYNC:
  return {
    ...state,
    currencieList: action.currencies,
  };

这是我getcurrencies在组件中调用的方式:

     componentDidMount() {
    const { getCurrencies} = this.props.actions
    setInterval(() => {
      getCurrencies();
    }, 30000);
  }

问题 - - - - -

问题是每当componentDidMount执行getcurrencies. 我收到错误消息can not slice .... undefined

const { currencieList, currentPage, itemsPerPage } = this.props;
const indexOfLastItem = currentPage * itemsPerPage;
const indexOfFirstItem = indexOfLastItem - itemsPerPage;
const currentItems = currencieList.slice(indexOfFirstItem, indexOfLastItem);

我 console.log-ed currencieList 并且在渲染之前它是空数组,它应该是但是在渲染之后它变得未定义,我不知道为什么。我还检查了我是否在我的 redux-saga 中正确获取了数据并且它是正确的。我正在检索它不是未定义的数据有什么建议吗?

标签: reactjsredux

解决方案


在 ComponentDidMount 中这样写:

componentDidMount() {
const { getCurrencies} = this.props.actions
setInterval(() => {
  getCurrencies([]);
}, 30000);

} 然后在你的传奇中写成这样:

 yield put(getCurrencies(data.data);

然后在减速器中写:

case actionTypes.LOAD_DATA_ASYNC:
  return {
    ...state,
    currencieList: action.payload,
  };

推荐阅读