简体   繁体   English

在Material UI中使用下拉组件在React JS中设置和更新状态

[英]Setting and updating state in React JS with Dropdown component from Material UI

I have this piece of code that calls a web service and displays the names coming from that WS into a Dropdown component from Material UI, 我有一段代码调用了一个Web服务,并将该WS的名称显示在Material UI的Dropdown组件中,

What I want to do is to set the default value of the dropdown with the first element coming from the WS and also be able to select any of the options in dropdown, I read something about " State " but don't get it really good at a code level. 我想做的是使用来自WS的第一个元素来设置下拉菜单的默认值,并且还能够选择下拉菜单中的任何选项,我读了一些有关“ 状态 ”的内容,但并没有得到很好的理解在代码级别。

I'm new to React and learning by myself but some help would be nice. 我是React和学习的新手,但有些帮助会很好。

    import React, { Component } from 'react';
    import DropDownMenu from 'material-ui/DropDownMenu';
    import MenuItem from 'material-ui/MenuItem';

    export default class WebserviceTest extends Component {

      constructor(props) {
        super(props);
        this.state = {
        data: [],
       };
       this.renderOptions = this.renderOptions.bind(this);
     }

     componentDidMount() {
     const url = 'https://randomuser.me/api/?results=4';

     fetch(url)
       .then(Response => Response.json())
       .then(findResponse => {
         console.log(findResponse);
         this.setState({
           data: findResponse.results
         });
       });
    }
    //will set wahtever item the user selects in the dropdown
    handleChange(event, index, value) {this.setState({ value });}
    //we are creating the options to be displayed
    renderOptions() {
     return this.state.data.map((dt, i) => {
       return (
         <div key={i}>
           <MenuItem
             label="Select a description"
             value={dt.name.first}
             primaryText={dt.name.first} />
         </div>
       );
     });
    }

    render() {
     return (
       <div>
         <DropDownMenu value={this.state.name} onChange={this.handleChange}>
           {this.renderOptions()}
         </DropDownMenu>
       </div>
     );
   }
  }

Thanks in advance. 提前致谢。

Regards. 问候。

this.setState controls the variable this.state in a special way. this.setState以特殊方式控制变量this.state Whenever you use this.setState it will run render again to check for changes accordingly. 每当您使用this.setState ,它将再次运行render以检查相应的更改。 Your dynamic content that you want to be responsive should be placed in this.state and those should be shown in your render function. 您希望响应的动态内容应放置在this.state并且这些内容应显示在render函数中。

There are many ways to go about solving your question, but the most important principle to use is to place what you currently want to render (or the id/index number) in this.state and use this.setState to change it as needed. 解决问题的方法有很多种,但是最重要的使用原则是将当前要呈现的内容(或ID /索引号)放在this.state并根据需要使用this.setState进行更改。

value={this.state.name} should be a single value from your data structure that you return from your fetch , assuming this is what is shown on the screen. 假设这是屏幕上显示的value={this.state.name}应该是您从数据fetch返回的数据结构中的单个值。

Also, you forgot to bind this.handleChange in your constructor. 另外,您忘记在构造函数中bind this.handleChange

Stating props in your constructor is perfectly fine to do. 在构造函数中声明props是一件非常好的事。 You only do that when you want to use something from this.props in your constructor. 仅在要在构造函数中使用this.props中的内容时才这样做。 You aren't, so it's perfectly safe to leave it as constructor() and super() 您不是,因此将其保留为constructor()super()是绝对安全的

You need to set state of selected dropdown option. 您需要设置所选下拉选项的状态。 And set first value of data as selected value. 并将数据的第一个值设置为选定值。

componentDidMount() {
 const url = 'https://randomuser.me/api/?results=4';

 fetch(url)
   .then(Response => Response.json())
   .then(findResponse => {
     console.log(findResponse);
     this.setState({
       data: findResponse.results,
       selected: findResponse.results[0].name.first // need to be sure it's exist
     });
   });
}
handleChange(event, index, value) {this.setState({ selected: value });}
.
.
.
render() {
 return (
   <div>
     <DropDownMenu value={this.state.selected} onChange={this.handleChange}>
       {this.renderOptions()}
     </DropDownMenu>
   </div>
 );

} }

UPDATED CODE 更新的代码

import React, { Component } from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';

export default class WebserviceTest extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      selected: '',
    };
    this.renderOptions = this.renderOptions.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    const url = 'https://randomuser.me/api/?results=4';

    fetch(url)
      .then(Response => Response.json())
      .then(findResponse => {
        console.log(findResponse);
        console.log(findResponse.results[0].name.first);
        this.setState({
          data: findResponse.results,
          selected: findResponse.results[0].name.first // need to be sure it's exist
        });
      });
  }
  handleChange(value) {this.setState({ selected: value });}

  //we are creating the options to be displayed
  renderOptions() {
    return this.state.data.map((dt, i) => {
      return (
        <div key={i}>
          <MenuItem
            value={dt.name.first}
            primaryText={dt.name.first} />
        </div>
      );
    });
  }

  render() {
    return (
      <div>
        <DropDownMenu value={this.state.selected} onChange={this.handleChange}>
          {this.renderOptions()}
        </DropDownMenu>
      </div>
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM