【问题标题】:map is not a function how to solve in react / typescript / reduxmap 不是函数如何在 react/typescript/redux 中解决
【发布时间】:2021-07-24 05:25:34
【问题描述】:

我想使用 typescript / react / redux_thunk 获取 api 数据并使用该数据制作一个简单的应用程序

这是我的代码:

type.tsx: 
       export interface Iproduct {
      id: number;
      title: string;
      price: number;
      description: string;
      category: string;
      image: string;
    }

Actions.ts

 import { Iproduct } from "../types/type";
     export const getProduct = () => (dispatch: any) => {
          axios
            .get<Iproduct[]>("https://fakestoreapi.com/products")
            .then((res) => dispatch({ type: "GET_PRODUCT", payload: res.data }))
            .catch((err) => {
              console.log(err);
            });
        };

减速机:

import { Iproduct } from "../types/type";

interface Iproducs {
  products: any[];
}

const INITALIZE_STATE: Iproducs = {
  products: [],
};

type Action = { type: string; payload: any[] };

export const reducer = (state = INITALIZE_STATE, action: Action) => {
  switch (action.type) {
    case "GET_PRODUCT":
      return { ...state, products: action.payload };
    default:
      return state;
  }
};

App.tsx:

 const state = useSelector((state: Iproduct[]) => state);
      const dispatch = useDispatch();
      const [products, setproducts] = useState<Iproduct[]>([]);
    
      useEffect(() => {
        dispatch(getProduct());
      }, []);
    
      useEffect(() => {
        setproducts(state);
        products.forEach((e: Iproduct) => console.log(e));
      });

我想在 app.tsx 文件中使用 useSelector 接收到的数据进行映射,但出现错误

“TypeError:products.map 不是函数”

如果你能告诉我我是在哪里做的,我会很高兴,因为我刚刚学会了打字稿,所以我无法解决这些错误。

注意:我在项目中使用redux-thunk

【问题讨论】:

  • 我没有看到你在代码中的任何地方调用products.map..?
  • fwiw 从另一个状态派生的状态是一种反模式。在这里,您正在从 redux 状态创建一个反应状态,这不好。

标签: reactjs typescript redux redux-thunk tsx


【解决方案1】:

尝试在reducer中替换下面的代码

export const reducer = (state = INITALIZE_STATE, action: Action) => {
     switch (action.type) {
      case "GET_PRODUCT":
        return { ...state, products: [action.payload] };
      default:
        return state;
    }
  }; 

【讨论】:

    【解决方案2】:

    您可能发送了不同的代码,但我想我明白了。当组件第一次加载时,它是未定义的,因为您没有提出任何请求并且产品数据没有更改。解决这个问题的最简单方法是使用

    state =&gt; (state.products || []).map(value =&gt; ...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 2019-12-15
      • 2017-12-30
      相关资源
      最近更新 更多