我正在为我的应用程序使用React-typescript。对于状态管理,我正在使用Redux-toolkit。我正在获取一个open api并将其存储在我的redux存储中。我创建了调度功能。从组件中,当我单击调度功能时,它将显示随机的狗图像。但问题是映射后,当我使用此img src时。我收到打字稿错误:Type 'Data' is not assignable to type 'string'.
我不知道自己在做什么错。我在codesandbox中上传了我的代码,尽管它可以在codesandbox中使用,但在我的应用程序中无法使用。
Ps。我没有上传商店设置代码,因为它可以找到☺️。
这是我的减速器
/* eslint-disable @typescript-eslint/indent */
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { AppThunk } from "store/store";
interface IMeta {
loading: boolean;
error: boolean;
message: string;
}
interface Data {
src: string;
}
interface IDogs {
meta: IMeta;
dogs: Data[];
}
const initialState: IDogs = {
"meta": {
"loading": false,
"error": false,
"message": ``
},
"dogs": []
};
const dogSlice = createSlice({
"name": `random-dogs`,
initialState,
"reducers": {
loadState(state) {
state.meta = {
"loading": true,
"error": false,
"message": ``
};
state.dogs = [];
},
fetchData(state, action: PayloadAction<Data[]>) {
state.meta.loading = false;
state.dogs = action.payload;
console.log(`dogs`, action.payload);
},
loadFailed(state, action: PayloadAction<string>) {
state.meta = {
"loading": false,
"error": true,
"message": action.payload
};
state.dogs = [];
}
}
});
export const { loadState, fetchData, loadFailed } = dogSlice.actions;
export default dogSlice.reducer;
export const fetchDogs = (): AppThunk => async (dispatch) => {
const url = `https://dog.ceo/api/breeds/image/random/5`;
try {
dispatch(loadState);
const response = await fetch(url);
const data = await response.json();
console.log(data);
console.log(data.message);
const singleData = data.message.map((i) => i);
dispatch(fetchData(singleData));
} catch (error) {
dispatch(loadFailed(`dogs are unavailable`));
console.log({ error });
}
};
这是我正在使用的Redux存储区
import React, { memo } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchDogs } from 'store/dogs';
import { RootState } from 'store/combineReducer';
export default memo(() => {
const state = useSelector((rootState: RootState) => ({
"dogs": rootState.fetchDogs.dogs,
"meta": rootState.fetchDogs.meta
}));
const dispatch = useDispatch();
console.log(`Dog component`, state.dogs[0]);
return (
<div>
{state.meta.loading ? <p>loading....</p> :
state.dogs.map((i, index) =>
<div key={index}>
<ul>
<li>{i}</li> // I can see the strings
</ul>
<img style={{ "width": 50, "height": 50 }} src={i} /> //getting error in here
</div>)}
<br></br>
<button onClick={() => dispatch(fetchDogs())}> display random dogs</button>
</div>
);
});
答案 0 :(得分:0)
情况如下:
您现在正在传递IDogs.dogs。您需要更深入到IDogs.dogs.src以获取所需的源字符串。
因此App.tsx的第25行应如下所示,并且一切正常:
<img style={{ width: 50, height: 50 }} src={i.src} alt="dog" />
PS:codesandbox示例仍然有效,因为它显然在某种程度上假设您需要src属性,但是如您所见,仍然会收到错误。
编辑:经过一番摆弄后,答案如下。但是,它与上面写的内容有关。
我下载了您的项目,并尝试在我的PC上以npm运行。我做了两件事使它起作用:
src={String(i)}