DropDown不会从API调用中填充数据

时间:2019-03-25 09:57:22

标签: reactjs

我是React的新手。我正在尝试进行api调用,并将数据填充到下拉菜单中。 api调用成功,我也可以在“网络”标签中看到响应。但响应不会被填充到下拉列表中。

我想将json响应中的“ abc”,“ def”等填充到我的下拉菜单中。

API响应

{
   {
    “ABC”: {
        "detail": "/diagnosticWorkflows/abc”
    },
    “DEF”: {
        "detail": "/diagnosticWorkflows/def”
    },
    “LMN”: {
        "detail": "/diagnosticWorkflows/lmn”
    },
    “PQR”: {
        "detail": "/diagnosticWorkflows/pqr”
    }
}

UI代码

class ABC extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      diagnosticWorkflow: [],
      selectedWorkflow: ""
    };
  }

  componentDidMount(nextProps) {
    api
      .workflowsApi("https://localhost:8443/api/diagnostic-workflows/")
      .then(res => {
        let workflowFromApi = Object.keys(res).map(workflow => {
          return { value: workflow, label: workflow };
        });

        this.setState({
          diagnosticWorkflow: [
            { value: "", label: "(Select Your Workflow)" }
          ].concat(workflowFromApi)
        });
      })
      .catch(error => {
        Console.log(error);
      });
  }

  render() {
    return (
      <div className={style.searchComponents}>
        <div className={style.searchFilter}>
          <label>
            <span>Diagnostic Requests</span>
          </label>
          <Dropdown
            auto={false}
            source={this.state.diagnosticWorkflow}
            allowBlank={false}
            value={this.state.selectedWorkflow}
            onChange={this.updateSearchParameters.bind(
              this,
              "selectedWorkflow"
            )}
            className={style.searchFilterDropdown}
          />
        </div>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

 let workflowFromApi = Object.keys(res).map(workflow => {
          return { value: workflow, label: workflow };
        });

您的此代码可能无法正常工作,因为res {{....}} Object.keys(res)将为空。您能否以

的方式做出回应
{   
    “ABC”: {
        "detail": "/diagnosticWorkflows/abc”
    },
    “DEF”: {
        "detail": "/diagnosticWorkflows/def”
    },
    “LMN”: {
        "detail": "/diagnosticWorkflows/lmn”
    },
    “PQR”: {
        "detail": "/diagnosticWorkflows/pqr”    
    }
}

这样,您的Object.keys(res)将返回键数组。