【发布时间】:2020-11-21 05:43:47
【问题描述】:
这是我的初始状态:
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 reducer:
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 中正确获取数据并且它是正确的。我正在检索它不是未定义的数据 请问有什么建议吗?
【问题讨论】:
-
你期待什么?您在 componentdidMount 中调用 getCurrencies 时没有参数(未定义)!数据从哪里来?不懂的不要用yield!
-
我刚接触它,我正在努力学习它
-
redux react 的工作原理是这样的:componentdidMount => 检索数据 => 使用数据触发 redux 操作 => 更新 store => 更新组件状态
-
而在我的情况下,我只需触发 componentdidMount 中的操作对吗?