React TypeScript:将字符串数组保存为状态并在无序列表中显示该数组

时间:2019-11-07 14:47:29

标签: reactjs typescript

我正在尝试将数组保存为状态,然后我想以某种方式遍历dom中保存为状态的数组,以使用每个数组中的一项来创建无序列表

  • 下面的示例中的数组值只是为了简化起见,它们实际上来自数据库,我不提前知道这些值,但我确实知道它们是字符串。

    import React, { useState } from 'react';
    const Worbli: React.FC = () => {
    
      const [state, setState] = useState({
         myArray = '';
      });
      const theArrayToSave = ['apple', 'orange', 'peach'] 
      setState({ ...state, myArray: theArrayToSave });
    
      return (
        <ul>
          { state.myArray.map( (fruit:string,index:number) => (<li key={index} >{fruit}</li>)) }
        </ul>
      )
    }
    

    我得到的错误是

    Argument of type '{ myArray: string[]; accountNameError: string; loading: boolean; }' is not assignable to parameter of type 'SetStateAction<{ accountNameError: string; loading: boolean; myArray: string; }>'.
      Type '{ myArray: string[]; }' is not assignable to type '{ myArray: string; }'.
        Types of property 'myArray' are incompatible.
          Type 'string[]' is not assignable to type 'string'.ts(2345)
    
  • 3 个答案:

    答案 0 :(得分:2)

    您应该这样声明自己的状态:

    const [state, setState] = useState({
      myArray: [];
    });
    

    但是,正如您之前提到的,这使它成为never[]类型而不是string[]类型,并且仍然会引发错误。为了解决这个问题,您应该像这样在状态声明中添加类型:

    interface IState {
      accountNameError: string;
      loading: boolean;
      myArray: string[];
    }
    
    const [state, setState] = useState<IState>({
      accountNameError: "",
      loading: false,
      myArray: []
    });
    

    这样,您可以专门告诉TypeScript状态值应该是什么样。

    答案 1 :(得分:1)

    您必须用一个空数组初始化状态,而不是用一个空字符串初始化状态。它应该可以工作

    const [state, setState] = useState<{myArray:string[]}>({
         myArray: [];
      });
    

    答案 2 :(得分:0)

    首先声明您的useState类型,然后设置默认数组,如下所示:

    实时预览示例:https://codesandbox.io/s/gallant-river-p3cfl

    import React, { useState } from "react";
    import { render } from "react-dom";
    
    import "./styles.css";
    
    type IState = {
      myArray: string[];
    };
    
    const Worbli: React.FC = () => {
      const [state, setState] = useState<IState>({
       myArray: ["apple", "orange", "peach"]
      });
    
      return (
        <ul>
          {state.myArray.map((fruit: string, index: number) => (
            <li key={index}>{fruit}</li>
          ))}
         <button
           onClick={() =>
           setState({ myArray: [...state.myArray, "Random Fruit Name?"] })
         }
        >
          Add to state
      </button>
    </ul>
    );
    };
    
    const rootElement = document.getElementById("root");
    render(<Worbli />, rootElement);