ReactJs:将数据Webapi返回到使用Tcomb-Form选择

时间:2018-06-02 17:18:39

标签: reactjs react-select tcomb-form-native

我正在尝试将'swapi'API的结果放入Select组件中,但是当页面加载时,select输入无法选择。我正在使用tcomb表单进行渲染。这里是示例代码:

import React, { Component } from 'react';
import Dom from 'react-dom';

import logo from './logo.svg';
import './App.css'; 

//add bootstrap libraries to the project ( npm install bootstrap --save)
import '../node_modules/bootstrap/dist/css/bootstrap.css';
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css';

import * as f from "tcomb"
import * as t from "tcomb-form"
import { Async } from 'react-select';
//import components from libraries 
import {
    Grid,
    Button,
    ButtonToolbar,
    ButtonGroup,
    Alert,
    Panel,
    ProgressBar,
    Table,
    Col,
    Row
} from "react-bootstrap";

async function getPlanets(q) {
  try {
    await fetch('https://swapi.co/api/planets/')
      .then(response => {
          return response.json();
      }).then(data => {
          return {
            x: data.results.map((p,id) => {
                return {
                    label: p.name,
                    value: p.name
                };
            })
        };
      });
      
  } catch (err) {
      console.error("Failed to get projects", err);
      return Promise.reject(err);
  }
}

const myTextbox = t.form.Form.templates.textbox.clone({
  renderInput(locals) {
    return (
      <Async
        name="form-field-name"
        value={locals.value}
        loadOptions={getPlanets}
        onChange={x => locals.onChange(x == null ? null : x.value)}
      />
    );
  }
});

const formOptions = {
  order: [
      "contractNumber"
  ],
  fields: {
      contractNumber: {
          label: "xpto",
          template: myTextbox,
          error:
              "mensagem de erro"
      }
    }
  }

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state ={
      value: null,
      options: null
    }
  }  

  makeModel() {
    const spec = {
        contractNumber: t.String
    };

    return t.struct(spec);
  }
  

  render() {
    console.log(this.state.value)
    return (
      <Col md={12}>
        <t.form.Form
            type={this.makeModel()}
            options={formOptions}
            value={this.state.value}
        />
      </Col>
    );
  }
}
    
export default App;

任何帮助?谢谢:D

(不完全确定原因但是当我返回一个promise而不是在loadOptions函数中使用回调时它似乎开始工作。)

0 个答案:

没有答案