【问题标题】:react.js typescript problem with JSON ArrayJSON数组的react.js打字稿问题
【发布时间】:2020-03-21 09:42:48
【问题描述】:

我正在尝试让自己熟悉 react.js 和 typescript。 我试图声明一个 JSON 数组,但它给了我一个错误,说 ... 不能分配给 JSON

这是我的代码:

import React from 'react';
type MyProps = {
    message?: string;
};
type MyState = {
    chat_list : Array<JSON>
    count: number; // like this
};
class ChatList extends React.Component<MyProps, MyState> {
    state: MyState = {
        count: 0,
        chat_list : [
            {
                "name":"true",
                "active" : true
            }
        ]
    };
    ...

我该如何解决这个问题?

【问题讨论】:

    标签: reactjs typescript react-typescript


    【解决方案1】:

    您应该定义聊天项目的形状,JSON 是具有特定形状的实际全局对象(JSON.stringifyJSON.parse 等)

        interface ChatItem {
          name: string;
          active: boolean;
        }
    
        interface MyState {
          chat_list: Array<ChatItem>; // Or ChatItem[]
          count: number;
        }
    
       state: MyState = {
          count: 0,
          chat_list: [
            {
              name: 'true',
              active: true,
            },
          ],
        };
    

    【讨论】:

    • 谢谢它的工作,出于好奇只是问,而不是声明 interface 我可以使用每个声明的 class 吗?因为我已经有了ChatItem 的一类替代品ChatListItem
    • 不确定每个声明的类是什么意思?就像为班级定义一些东西一样?如果您的意思是这样,接口或类型可以限定在函数或文件内部
    • 我的意思是 pre-declared 类,我想从我所有的类中访问它..
    • 只是在另一个文件中声明,或者更好的方式,比如声明为 props 或其他东西,对于 react-typescript 来说是新的
    • 是的,对于共享类型,我建议您使用 types.ts 之类的文件并从那里导入,这也可以避免循环依赖问题。也可以选择“环境声明文件”,但我认为坚持下去更简单。
    猜你喜欢
    • 2022-11-19
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 2016-11-01
    • 2022-01-24
    • 2020-12-27
    • 2018-06-14
    相关资源
    最近更新 更多