【问题标题】:TypeScriptError: Type 'Data' is not assignable to type 'string'TypeScriptError:类型“数据”不可分配给类型“字符串”
【发布时间】:2020-11-10 21:07:59
【问题描述】:

我正在为我的应用程序使用 React-typescript。对于状态管理,我使用Redux-toolkit。我正在获取一个 open api 并将其存储在我的 redux 商店中。我创建了调度功能。从组件中,当我单击调度功能时,它将显示随机狗图像。但问题是在我使用这个 img src 映射之后。我收到打字稿错误:Type 'Data' is not assignable to type 'string'. 我不知道我做错了什么。我在codesandbox 中上传了我的代码,虽然它在codesandbox 中有效,但在我的应用程序中无效。

附言。我没有上传我的商店设置代码,因为它可以找到☺️。

这是我的减速机

    /* 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>
      );
    });

【问题讨论】:

  • i 实际上是一个整数。你可以尝试像&lt;img ... src={${i}} /&gt;

标签: react-redux redux-toolkit react-typescript


【解决方案1】:

情况如下:

  • 接口 IDog 具有 Data[] 类型的属性“dogs”。
  • 数据具有字符串类型的属性“src”。
  • img 的 Src 属性必须是字符串。

您现在正在传递 IDogs.dogs。你需要深入 IDogs.dogs.src 才能得到你想要的源字符串。

所以 App.tsx 的第 25 行应该是这样的,而且一切似乎都正常:

&lt;img style={{ width: 50, height: 50 }} src={i.src} alt="dog" /&gt;

PS:codesandbox 示例仍然有效,因为它显然做了某种假设,即您需要 src 属性,但正如您所见,您仍然会收到错误。


编辑:经过一番摆弄,答案如下。然而,它与上面写的内容有关。

我下载了你的项目并尝试在我的电脑上运行 npm。我做了两件事让它发挥作用:

  1. 我更新了第 25 行以使用演员表:src={String(i)}
  2. 我更新了反应脚本。请参阅此线程以供参考:TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

【讨论】:

  • 当我尝试使用&lt;li&gt;{i.src}&lt;/li&gt; 然后它也没有显示列表。
  • 确实,我认为这不是问题。铸造似乎解决了这个问题,你有没有在你的项目中尝试过? src={String(i)}
  • 我下载了你的项目并尝试在我的电脑上运行 npm。我做了两件事让它发挥作用。查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 2020-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多