创建的下拉列表可从api获取数据,但现在我想将下拉列表中的选定项目发送到数据库。怎么做?

时间:2019-03-29 06:29:33

标签: reactjs dropdown fetch-api

我试图获取数据并以某种状态存储,然后当我在下拉列表中选择一个选项时,我无法将其存储在变量中,并且单击“提交”按钮将其发送回数据库。谁能帮助我该怎么做?

  //fetches the data from an api and maps to dropdown
componentDidMount() {
 let initialPlanets = [];
  fetch('http://b0499a61.ngrok.io/api/assetType')
     .then(response => {
        return response.json();
    }).then(data => {
    initialPlanets = data.map((planet) => {
        return planet
    });
    console.log(initialPlanets);
    this.setState({
        planets: initialPlanets,
    });
});
}

 render() {
         return (
             <div id="react-search">
             <Options state={this.state}/>
             </div>
     )
    }
 }

    //mapping with dropdown
        let planets = this.props.state.planets;
         let optionItems = planets.map((planet) =>
            <option key={planet.asset_type}>{planet.asset_type} 
    </option>
            );
       return (
        <div>
          <select>
            {optionItems}
            </select>
       </div>
        )
       }
     }

  //here need to store the selected dropdown data in a variable
 class Requestbutton extends React.Component {
 constructor(props) {
 super(props);

this.state = {
  items:[],
  emp_id:'',
  asset_type: "",
  comments_emp: ""
};

 onChange(e) { 
 this.setState({
  [e.target.name] : e.target.value });
 }

  componentDidMount(){
  var p_id=localStorage.getItem('id')
   fetch(`http://b0499a61.ngrok.io/api/employee/${p_id}`)
  .then(res => res.json())
  .then(json => {
    this.setState({
      isLoaded : true,
      items: json[0],
    })
    console.log(this.state.items)
    });
  }

  onSubmit(e){
   e.preventDefault();
   const newpost ={
   emp_id : this.state.items.emp_id,
   asset_type : this.state.asset_type,
   comment_emp: this.state.comment_emp
   }
  console.log(newpost)
   fetch('http://b0499a61.ngrok.io/api/newAssetRequest',{
    method: 'POST',
    headers: {
    'content-type' : 'application/json'
   },
    body: JSON.stringify(newpost)
   })
   .then(res => res.json())
   .then(data => console.log(data));
   }

  render() {
   return(
          <label>Select Asset type</label>

          <Dropdown />

    }
   }  

我希望将所选选项从下拉列表发送到后端。

0 个答案:

没有答案