我的返回类型是对象数组的形式,但我无法映射数组来获取值



我试图获取数组中每个元素的值,但map()抛出了一个错误。我必须调用API并获取用户的详细信息。

但是我得到控制台上的数据,但当我试图打印它显示未定义或null。谁能告诉我如何映射这里的值?

types.ts

export const GET_DETAILS = "GET_DETAILS";
export const SET_LOADING = "SET_LOADING";
export const SET_ERROR = "SET_ERROR";
export const SET_ALERT = "SET_ALERT";

export interface UserData {
id: number;
name: string;
email: string;
address: {
street: string;
suite: string;
city: string;
zipcode: string;
geo: {
lat: string;
lng: string;
};
};
phone: string;
website: string;
company: {
name: string;
catchPhrase: string;
bs: string;
};
}
export interface userError {
cod: string;
message: string;
}
export interface UserState {
data: UserData | null;
loading: boolean;
error: string;
}
interface GetUserAction {
type: typeof GET_DETAILS;
payload: UserData;
}
interface SetLoadingAction {
type: typeof SET_LOADING;
}
interface SetErrorAction {
type: typeof SET_ERROR;
payload: string;
}
export type UserAction = GetUserAction | SetLoadingAction | SetErrorAction;
export interface AlertAction {
type: typeof SET_ALERT;
payload: string;
}
export interface AlertState {
message: string;
}

loginAction.ts

import { ThunkAction } from "redux-thunk";
import { RootState } from "..";
import {
UserAction,
GET_DETAILS,
SET_LOADING,
SET_ERROR,
UserData
} from "../types";
export const getUser = (
name: string
): ThunkAction<void, RootState, null, UserAction> => {
return async (dispatch) => {
try {
const res = await fetch(`https://jsonplaceholder.typicode.com/users`);
const resData: UserData = await res.json();
console.log(resData);
dispatch({
type: GET_DETAILS,
payload: resData
});
} catch (err) {
dispatch({
type: SET_ERROR,
payload: err.message
});
console.log(err);
}
};
};
export const setLoading = (): UserAction => {
return {
type: SET_LOADING
};
};
export const setError = (): UserAction => {
return {
type: SET_ERROR,
payload: ""
};
};

User.tsx

import React, { FC } from "react";
import styled from "styled-components";
import { UserData } from "../store/types";
interface UserProps {
data: UserData;
}
const User: FC<UserProps> = ({ data }) => {
return (
<>
<p>Name : {data.name}</p>
<p>ID: {data.id}</p>
<p>Email: {data.email}</p>
<p>Address: {data.address}</p>
<p>{data.company}</p>
<p>{data.phone}</p>
<p>{data.website}</p>
</>
);
};
export default User;

类型是错误的resData,你期待一个数组对吗?resData是undefined/null,所以你的map不工作。我会修复这部分,然后你就可以在它上面进行映射了。我会的。修复打字和2。确保获取请求成功。

最新更新