React-typescript-Redux-toolkit:无法获取嵌套 api
React-typescript-Redux-toolkit: failed to fetch nested api
我正在用 typescript 练习 redux-toolkit。我用过一个open api and for fetching data I used redux toolkit's createAsyncThunk
. I successfully able to fetched the data in app's component. When I console log it, I can able to see the data but as soon I map the data.result
I am getting error: TypeError: Cannot read property 'map' of undefined
. I think I have made Typescript error when I used the interface. But don't see where is the problem and Also in Chrome's reduxdevtools: data
expect object but I put arrays. This my redux-devtools looks like。
我在 Codesand Box.
中分享了我的代码
PS: I am sharing only these two files below because I think this is where I making mistakes
这是我的 Reducer,我想我的类型有误
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const dataFetch = createAsyncThunk(
`store/dataFetch`,
async () => {
const url = `https://rickandmortyapi.com/api/character`;
const response = await fetch(url);
const data = await response.json();
return data;
}
);
interface Meta {
loading: boolean;
error: boolean;
message: string;
}
// This is where I am making mistake
interface Results {
name: string;
image: string;
gender: string;
species: string;
status: string;
}
interface Info {
count: number;
pages: number;
}
interface User {
results: Results[];
info: Info;
}
export interface IUser {
meta: Meta;
data: User[];
}
const initialState: IUser = {
"meta": {
"loading": false,
"error": false,
"message": ``
},
"data": []
};
const UserSlice = createSlice({
"name": `JsonPlacehoder user`,
initialState,
"reducers": {
},
"extraReducers": (builder) => {
builder.addCase(dataFetch.pending, (state) => (
{
...state,
"meta": {
...state.meta,
"loading": true
}
}
));
builder.addCase(dataFetch.fulfilled, (state, { payload }) => (
{
...state,
"meta": {
...state.meta,
"loading": false,
"error": false,
"message": ``
},
"data": payload
}
));
builder.addCase(dataFetch.rejected, (state, { error }) => {
window.alert(error?.message);
return {
...state,
"meta": {
"loading": false,
"error": true,
"message": error?.message || ``
}
};
});
}
});
export default UserSlice.reducer;
这是我的组件,当我使用 map 函数时出现错误
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { dataFetch } from './store/reducers';
import { IRootState } from './store/combineReducers';
function App() {
const { data, meta } = useSelector((rootState: IRootState) => rootState.fetchUser);
console.log(data);
const dispatch = useDispatch()
useEffect(() => {
dispatch(dataFetch())
}, [dispatch])
return (
<div className="App">
{
data.results.map(i => { //GETTING ERROR
return <div>
<h1>{i.name}</h1>
</div>
})
}
</div>
);
}
export default App;
那是因为您试图 .map
在获取开始之前就遍历数据。
您的 useEffect
在第一次渲染后触发。在此之前,您已经尝试 .map
一次。
即使这样,在加载期间,您的组件也可能会重新呈现。
你的一些 reducer 倾向于实际删除 data
属性而不是保留 data: []
(我正在那里等待)导致 data
未定义在一些渲染上。
A TypeError
实际上不是 TypeScript 错误(这些错误总是以“ts”开头,后跟数字),而是 JavaScript 运行时错误。所以你真的有一个“运行时崩溃”。
我正在用 typescript 练习 redux-toolkit。我用过一个open api and for fetching data I used redux toolkit's createAsyncThunk
. I successfully able to fetched the data in app's component. When I console log it, I can able to see the data but as soon I map the data.result
I am getting error: TypeError: Cannot read property 'map' of undefined
. I think I have made Typescript error when I used the interface. But don't see where is the problem and Also in Chrome's reduxdevtools: data
expect object but I put arrays. This my redux-devtools looks like。
我在 Codesand Box.
PS: I am sharing only these two files below because I think this is where I making mistakes
这是我的 Reducer,我想我的类型有误
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const dataFetch = createAsyncThunk(
`store/dataFetch`,
async () => {
const url = `https://rickandmortyapi.com/api/character`;
const response = await fetch(url);
const data = await response.json();
return data;
}
);
interface Meta {
loading: boolean;
error: boolean;
message: string;
}
// This is where I am making mistake
interface Results {
name: string;
image: string;
gender: string;
species: string;
status: string;
}
interface Info {
count: number;
pages: number;
}
interface User {
results: Results[];
info: Info;
}
export interface IUser {
meta: Meta;
data: User[];
}
const initialState: IUser = {
"meta": {
"loading": false,
"error": false,
"message": ``
},
"data": []
};
const UserSlice = createSlice({
"name": `JsonPlacehoder user`,
initialState,
"reducers": {
},
"extraReducers": (builder) => {
builder.addCase(dataFetch.pending, (state) => (
{
...state,
"meta": {
...state.meta,
"loading": true
}
}
));
builder.addCase(dataFetch.fulfilled, (state, { payload }) => (
{
...state,
"meta": {
...state.meta,
"loading": false,
"error": false,
"message": ``
},
"data": payload
}
));
builder.addCase(dataFetch.rejected, (state, { error }) => {
window.alert(error?.message);
return {
...state,
"meta": {
"loading": false,
"error": true,
"message": error?.message || ``
}
};
});
}
});
export default UserSlice.reducer;
这是我的组件,当我使用 map 函数时出现错误
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { dataFetch } from './store/reducers';
import { IRootState } from './store/combineReducers';
function App() {
const { data, meta } = useSelector((rootState: IRootState) => rootState.fetchUser);
console.log(data);
const dispatch = useDispatch()
useEffect(() => {
dispatch(dataFetch())
}, [dispatch])
return (
<div className="App">
{
data.results.map(i => { //GETTING ERROR
return <div>
<h1>{i.name}</h1>
</div>
})
}
</div>
);
}
export default App;
那是因为您试图 .map
在获取开始之前就遍历数据。
您的 useEffect
在第一次渲染后触发。在此之前,您已经尝试 .map
一次。
即使这样,在加载期间,您的组件也可能会重新呈现。
你的一些 reducer 倾向于实际删除 data
属性而不是保留 data: []
(我正在那里等待)导致 data
未定义在一些渲染上。
A TypeError
实际上不是 TypeScript 错误(这些错误总是以“ts”开头,后跟数字),而是 JavaScript 运行时错误。所以你真的有一个“运行时崩溃”。