简体   繁体   English

Typescript 错误类型无法分配给 state - 使用状态

[英]Typescript error type not assign able to state - usestate

I am new to type script and I am trying to set the state in react using use state hook and type script.我是键入脚本的新手,我正在尝试使用 state 钩子和类型脚本来设置 state 做出反应。

const intialState: State ={
    items: [],
    value: "",
    error: null
}

const [data, setData]= useState([intialState]);

return (
    <>
        {
            data.items.map(x) => (
                //my html component to be displayed.
            )
        }
    </>
)

but I am getting the below error.但我收到以下错误。 Can any one tell me.有谁能告诉我。

  1. Is it valid to set an object inside a usestate like I have done?像我所做的那样在使用状态中设置 object 是否有效?
  2. Why I am getting the typescript error?为什么我收到 typescript 错误?

在此处输入图像描述

First, we should check if there is an interface mismatch between State , and the initialState object.首先,我们应该检查State和初始状态initialState之间是否存在接口不匹配。 It will help if you can post the type definition of State .如果您可以发布State的类型定义,将会有所帮助。

In addition, you should supply the useState hook with the generic type parameter of State[]此外,您应该为useState钩子提供State[]的泛型类型参数

const [data, setData]= useState<State[]>([intialState]);

You need to specify type for useState.您需要为 useState 指定类型。 Since its an array of your state object you can write it like由于它是你的 state object 的数组,你可以这样写

const [data, setData]= useState<State[]>([intialState]);

Also make sure you define a type for your state's object还要确保为您所在州的 object 定义一个类型

interface ErrorType {
   status: Number // more keys and their types here
}
interface MyDataType {
  items: ItemType[],
  error: ErrorType | null,
  value: string,
}

post that you can use it with useState like发布您可以将其与 useState 一起使用的帖子

const [data, setData]= useState<MyDataType[]>([intialState]);

Your data is an array of objects and when you update the state you need to merge the values.您的数据是一个对象数组,当您更新 state 时,您需要合并这些值。 For that you can use functional setState为此,您可以使用功能 setState

var updatedDataObj = { items: ["a","b","c"], error: "404", value: "xyx", };
setData(prevData => [...prevData, updatedDataObj]);

I guess this was what you tried to achieve.我想这就是你试图达到的目标。 Make sure you define your State type correctly, not importing from some other packages确保正确定义 State 类型,而不是从其他一些包中导入

interface State {
    items: any[];
    value: string;
    error: string | null;
}


const MyComponent: (props) => {
    const intialState: State ={
        items: [],
        value: "",
        error: null
    }
    const [data, setData] = useState(intialState)


return (
   <>
        {
            data.items.map(x) => (
                //my html component to be displayed.
            )
        }
    </>
    )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM