首页 文章

React / Typescript:如何获取json文件数据

提问于
浏览
1

如何从状态中的json文件中读取数据?我知道如何只做反应,但没有做反应使用打字稿 . 如果它不会改变,我应该首先将它置于州吗?

import * as React from 'react';
import * as data from '../../team.json';

interface Props {
  //props
}

interface State {
   nextRacers: Array<object>;
   jockeys: Array<any>;
}

console.log(data) // I can see my data here in dev tools

export class Race extends React.Component<Props, State> {

  constructor(props: Props) {
      super(props);
      this.state = {
          jockeys: data, 
          nextRacers: [],
      };
  }
  
}

Error I get;

输入'{jockeys:typeof“.json”; nextRacers:never []; ''不能赋值为'Readonly' . property '骑师'的类型是不相容的 . 键入'typeof“.json”'不能指定为'any []' . 类型'typeof“* .json”'中缺少属性'includes' .

我是打字稿和反应的新手,语法仍然在弄乱我的脑袋 .

1 回答

  • 0

    首先,您需要将 data 强制转换为 any ,然后再次将其强制转换为 jockeys 字段的类型,即 Array<any> . 尝试将分配更新为 this.state ,如下所示:

    this.state = {
        jockeys: data as any as Array<any>, 
        nextRacers: [],
    };
    

相关问题