reactjs - 我的 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 中正确获取了数据并且它是正确的。我正在检索它不是未定义的数据有什么建议吗?
解决方案
在 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,
};
推荐阅读
- .htaccess - .htaccess 站点地图重写/重定向
- docker - 连接到专用 Docker 机器时如何默认使用 Docker Compose 生产配置?
- reactjs - axios 删除 API 不起作用(使用 JSON 服务器)
- c# - 在索引处查找子字符串,然后检索以下数字
- excel - 根据值突出显示第 3 列中的不同颜色的值
- select - 如何以 sass 格式设置由 simple_form 生成的选择元素?
- assembly - 在 gdb 中调试 - 如何知道测试是否成功
- ajax - Shopify 中的多维数组
- cucumber-java - Cucumber 和 QAF BDD2 有什么区别
- java - 计算两个用户输入之间的奇数和