我正在尝试将数组保存为状态,然后我想以某种方式遍历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)
答案 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);