JSON数组的react.js打字稿问题

时间:2020-03-21 09:42:48

标签: reactjs typescript react-typescript

我试图让自己熟悉带有打字稿的react.js。 我试图声明一个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
            }
        ]
    };
    ...

我该如何解决?

1 个答案:

答案 0 :(得分:2)

您应该定义聊天项的形状,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,
        },
      ],
    };
相关问题