Redux发起第三方GET API无响应及selector.map报错问题求助
问题原因
- API请求未触发的核心原因:
- 原生Redux默认不支持异步action,你未配置
redux-thunk中间件处理异步逻辑 - action函数中错误使用了React Hook
useDispatch,Hook只能在React组件或自定义Hook中调用,无法在普通函数中生效 - 组件内直接调用
getData(),没有通过dispatch触发Redux的action执行流程
- 原生Redux默认不支持异步action,你未配置
selector.map is not a function错误原因:useSelector(state => state.get)取到的是reducer返回的对象{airlines: []},对象没有map方法,你需要取的是该对象下的airlines数组属性。
修复步骤
1. 安装依赖
先安装异步处理需要的redux-thunk中间件:
npm install redux-thunk
2. 修改入口store配置(index.js)
引入并应用thunk中间件:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Provider } from "react-redux"; import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import reducer from './reducers'; // 兼容Redux DevTools调试工具 const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk))); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); reportWebVitals();
3. 修改actions文件
移除错误的useDispatch调用,直接使用thunk异步函数自带的dispatch参数:
export const getData = () => async(dispatch) => { await fetch('https://api.instantwebtools.net/v1/airlines', { method : 'GET' }).then( res => res.json() ).then( data => dispatch({ type : "GET_DATA", payload : data }) ); };
4. 修改screen.jsx组件
调整取值逻辑,新增dispatch触发action,修正map遍历写法:
import React from "react"; import { useSelector, useDispatch } from "react-redux"; import { getData } from "./actions"; import { useEffect } from "react"; const Screen = () => { // 直接取reducer中的airlines数组 const airlines = useSelector(state => state.get.airlines); const dispatch = useDispatch(); useEffect(() => { // 通过dispatch触发异步请求 dispatch(getData()) }, [dispatch]); return ( <div> {/* 遍历数组直接取当前项的属性即可 */} {airlines.map((item, index) => <ul key={item.id || index}> <li>{item.name}</li> </ul> )} </div> ); }; export default Screen;
内容的提问来源于stack exchange,提问作者coolhack7
相关产品推荐
相关产品推荐

