如何声明值以初始化数组的状态?

时间:2019-01-25 18:58:16

标签: reactjs flowtype

我使用Flow进行输入,并且总是声明类型,然后使用一些值初始化状态,但是我没有进入数组

type State = {
    id_evaluation: string,
    questions: Array<{
        id: number,
        question_content_id: number,
        component: Array<{
            type_desc: string,
            content: string,
        }>,
    }>,
    current_question: number,    
};

class Evaluation extends Component < Props, State > {
    state = {
        id_evaluation: '',
        questions: [
            id: 0,
            question_content_id: 0,
            component: [
            type_desc: '',
            content: '',
            ]
        ],
        current_question: Math.floor(Math.random() * 30) + 0,
    }

但是以下错误出现在“问题”中的所有元素中:

[Flow] Unexpected token : [ParseError]

1 个答案:

答案 0 :(得分:1)

您的数组声明无效,您必须将内部对象包装到{...}中:

state = {
    id_evaluation: '',
    questions: [{
        id: 0,
        question_content_id: 0,
        component: [{
          type_desc: '',
          content: '',
        }]
    }],
    current_question: Math.floor(Math.random() * 30) + 0,
}

或者换句话说,类型是:

type Component = {
  type_desc: string,
  content: string
}

type Question = {
  id: number,
  question_content_id: number,
  component: Array<Component>
}

type State = {
  id_evaluation: string,
  questions: Array<Question>,
  current_question: number,    
};

数据是:

const component: Component = {
   type_desc: '',
   content: ''
};

const question: Question = {
   id: 0,
   question_content_id: 0,
   component: [component]
};

const state: State = {
   id_evaluation: '',
   questions: [question],
   current_question: Math.floor(Math.random() * 30) + 0
}