簡體   English   中英

有條件的API調用並在react-select中發送數據

[英]Conditional API call and send data in react-select

 import React, { Component} from 'react'; import Select from 'react-select'; import 'react-select/dist/react-select.css'; const partsType = [ {value: 'front_parts', label: 'Part Condition-Front'}, {value: 'left_parts', label: 'Part Condition-Left'}, {value: 'back_parts', label: 'Part Condition-Back'}, {value: 'right_parts', label: 'Part Condition-Right'}, {value: 'top_bottom_parts', label: 'Part Condition-Top/Bottom'}, {value: 'glass', label: 'Glass Condition'}, {value: 'electrical_parts', label: 'Electrical Parts'}, {value: 'non_electrical_parts', label: 'Non-Electrical Parts'} ]; const getParts = () => { return fetch( "http://localhost:4000/left_parts", { method: 'get' } ) .then(response => { if(response.status >= 400) { throw new Error("error"); } return response.json() }) .then(parts => { let partsName = []; for(let part of parts) { partsName.push({value: part.promptCode, label: part.text}) } return {options: partsName}; }) .catch(err => { console.log('could not fetch parts'); console.log(err); return {options: []} }) }; class Assess extends Component { constructor(props) { super(props); this.state = { partsType:'front_parts' }; this.handlePartsType = this.handlePartsType.bind(this); handlePartsType = (item) => { this.setState({ partsType: item.value }); }; render() { return ( <div> <Select clearable={false} searchable={false} value={this.state.partsType} options={partsType} onChange={this.handlePartsType} /> <Select.Async clearable={false} searchable={false} name="PartNamePolygon" value={this.state.PartNamePolygon} onChange={this.PartNamePolygonSelect} loadOptions={getParts} /> </div> ); } } 

我提供了摘要。 我現在正在做的是我做了兩個下拉菜單,使用第二個下拉菜單的第一個下拉菜單的數據將被更改。 現在,我無法根據this.state.partsType來調用不同的API,因為根據其狀態值,其值將在“ getParts”中傳遞。 如何實現呢? 將其值傳遞給它,以便將調用不同的API

這樣嘗試

import React, { Component} from 'react';  
        import Select from 'react-select';  
        import 'react-select/dist/react-select.css';

        const partsType = [
            {value: 'front_parts', label: 'Part Condition-Front'},
            {value: 'left_parts', label: 'Part Condition-Left'},
            {value: 'back_parts', label: 'Part Condition-Back'},
            {value: 'right_parts', label: 'Part Condition-Right'},
            {value: 'top_bottom_parts', label: 'Part Condition-Top/Bottom'},
            {value: 'glass', label: 'Glass Condition'},
            {value: 'electrical_parts', label: 'Electrical Parts'},
            {value: 'non_electrical_parts', label: 'Non-Electrical Parts'}
        ];

        const getParts = (type) => {
            return fetch(
              `http://localhost:4000/${type}`,
              {
                  method: 'get'
              }
            )
              .then(response => {
                  if(response.status >= 400){
                  throw new Error("error");
                  }
                  return response.json()
              })
              .then(parts => {
                  let partsName = [];


                  for(let part of parts) {
                  partsName.push({value: part.promptCode, label: part.text})
                  }


                  return {options: partsName};
              })
              .catch(err => {
                  console.log('could not fetch parts');
                  console.log(err);
                  return {options: []}
              })

        };

        class Assess extends Component {

            constructor(props){
            super(props);
            this.state = {
                partsType:'front_parts'

            };

        this.handlePartsType = this.handlePartsType.bind(this);

        handlePartsType = (item) => {
              this.setState({
                  partsType: item.value
              }, getParts(item.value));

              };

        render() {

            return (
            <div>
            <Select
            clearable={false}
            searchable={false}
            value={this.state.partsType}
            options={partsType}
            onChange={this.handlePartsType}
            />

        <Select.Async
                                  clearable={false}
                                  searchable={false}
                                  name="PartNamePolygon"
                                  value={this.state.PartNamePolygon}
                                  onChange={this.PartNamePolygonSelect}
                                  loadOptions={getParts}
                                />

        </div>
            );
          }
        }

有幾個問題:

this.handlePartsType = this.handlePartsType.bind(this); 是多余的。 另外,構造函數沒有右括號。 Select.Async不應該用於基於外部值加載選項,它會在輸入更改時加載選項。

下面是重寫的示例:

  const partsType = [ {value: 'front_parts', label: 'Part Condition-Front'}, {value: 'left_parts', label: 'Part Condition-Left'}, {value: 'back_parts', label: 'Part Condition-Back'}, {value: 'right_parts', label: 'Part Condition-Right'}, {value: 'top_bottom_parts', label: 'Part Condition-Top/Bottom'}, {value: 'glass', label: 'Glass Condition'}, {value: 'electrical_parts', label: 'Electrical Parts'}, {value: 'non_electrical_parts', label: 'Non-Electrical Parts'} ]; // test wrapper for fetch to be removed to talk to backend const fetch = () => Promise.resolve({json: () => Promise.resolve([{promptCode: 'test', text: 'Test option'}])}) const getParts = (partsType) => { return fetch( `http://localhost:4000/${partsType}`, { method: 'get' } ) .then(response => { if(response.status >= 400){ throw new Error("error"); } return response.json() }) .then(parts => { let partsName = []; for(let part of parts) { partsName.push({value: part.promptCode, label: part.text}) } return {options: partsName}; }) .catch(err => { console.log('could not fetch parts'); console.log(err); return {options: []} }) }; class Assess extends React.Component { state = { partsType:'front_parts' }; handlePartsType = (partsType) => { getParts(partsType).then(({options}) => this.setState({partsType, partsOptions: options}) ) }; componentDidMount() { this.handlePartsType(this.state.partsType); } render() { return ( <div> <Select clearable={false} searchable={false} value={this.state.partsType} options={partsType} onChange={({value}) => this.handlePartsType(value)} /> <Select clearable={false} searchable={false} name="PartNamePolygon" value={this.state.partNamePolygon} onChange={this.partNamePolygonSelect} options={this.state.partsOptions} /> </div> ); } } ReactDOM.render( <div> <Assess/> </div>, document.getElementById('root') ) 
 <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <script src="https://unpkg.com/classnames/index.js"></script> <script src="https://unpkg.com/react-input-autosize@1.0.0/dist/react-input-autosize.js"></script> <script src="https://unpkg.com/react-select@1.0.0-rc.3/dist/react-select.js"></script> <link rel="stylesheet" href="https://unpkg.com/react-select@1.0.0-rc.3/dist/react-select.css"> </head> <body> <div id='root'></div> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM