如何使用map()?

时间:2019-09-02 07:35:04

标签: javascript reactjs

我有一个函数mostraReferti,从数据库中获取项目列表并将其以状态存储到referti[]中。我需要在下拉列表中显示这些项目。我首先尝试在{this.state.referti}中编写<option>,但是得到的只是表的第一项。我需要使用map()。所以我尝试了这段代码:

class CredentialsPanel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      referti: []
     }
     this.handleInputChange = this.handleInputChange.bind(this);
     this.mostraReferti = this.mostraReferti.bind(this);
   }

   static getDerivedStateFromProps(nextProps) {
     const { account } = nextProps
     return { id: account.id }
  }

   handleInputChange(event) {
     const target = event.target;
     const value =
       target.type === 'checkbox'
         ? target.checked
         : target.value;
     const name = target.name;
  console.log("stato", this.state)
     this.setState({
       [name]: value,
     });
   }

   componentDidMount() {
     const { actions } = this.props

     requestAccountAccess((defaultAccount) => {
       actions.account.setDefaultAccount(defaultAccount)
       actions.contract.setContract(defaultAccount)
     })
    this.mostraReferti(this.state.id)   
   }

   mostraReferti(id) {
     console.log("id", id)
     axios.get('http://localhost:8080/api/REFERTOs/' + id)
       .then(response => {
         console.log("response1" + JSON.stringify(response.data))
        this.setState({ referti: response.data }, () => {
             console.log(this.state);
           })
         return response.data
       })
     }

   onEnter = (evt) => {
     if (evt.key === 'Enter') {
       const { allowToProceed } = this.state
       if (allowToProceed) { this.proceed() }
     }
   }

    proceed = () => {
     const { actions, history } = this.props
     const { codiceReferto } = this.state   
     actions.account.setCodiceReferto(codiceReferto)
     history.push('/consenso?panel=2')
   }

 render() {
     const { id, nextBtnDisabled } = this.state
     const refertiItems = this.state.referti.map((referti, i) => {
       return (
         <RefertiItems key={referti.hash_referto} item={referti} />
       )
     })

     return (
       <div className={styles}>
         <h2>Compila i campi per assegnare un consenso</h2>
         <Form onSubmit={this.handleSubmit}>
           <div className="form-section">

      <br />
          <div className= "custom-select"  >
            {refertiItems}
          </div>
         <br />
  </div>
         </Form>
     )
   }
 }

RefertiItems是:

 class RefertiItems extends Component {
    constructor(props) {
        super(props);
        this.state = {
            item: props.item
        } 
    }  

render(){
return (
    <div  classname= "custom-select">
   <Label for="type" text="Codice Referto" />
    <select
      name="codiceReferto"
       placeholder="Selezionare Referto"
      onKeyPress={this.onEnter}     //allows you to move to the next panel with the enter key
      value={this.codiceReferto}
      onChange={this.handleInputChange}>
      <option default value="vuoto"></option>
      <option value={this.state.item.hash_referto}> . 
   {this.state.item.tipo_referto}-{this.state.item.data_referto}</option>
    </select>
    </div>
)
}
}

我得到的是“ this.state.referti.map不是函数” ,并且系统为数据库表中的每个项目显示不同的选择。

3 个答案:

答案 0 :(得分:0)

您应该直接传递referti数组作为RefertiItems的支持。

ReferiItems类:

class RefertiItems extends Component {
  constructor(props) {
    super(props);
    this.state = {
      item: props.item
    };
  }

  render() {
    return (
      <div classname="custom-select">
        <Label for="type" text="Codice Referto" />
        <select
          name="codiceReferto"
          placeholder="Selezionare Referto"
          onKeyPress={this.onEnter} //allows you to move to the next panel with the enter key
          value={this.codiceReferto}
          onChange={this.handleInputChange}
        >
          <option default value="vuoto"></option>
          {
            this.props.item.map((item, key) => {
              // Use map here
              <option value={item.value} key={key}>{item.text}</option>
            })
          }
        </select>
      </div>
    );
  }
}

CredentialsPanel类的render方法如下:

class CredentialsPanel extends Component {
  // ...
  render() {
    return (
      // ...
      <div className="custom-select">
        <RefertiItems item={this.state.referti} />
      </div>
      // ...
    );
  }
}

答案 1 :(得分:0)

也许this.state.referti不是数组数据类型,所以它的map不是函数,您应该console.log(this.state.referti)检查其值。

如果使用TypeScript,则可以大大减少此类错误的类型。

答案 2 :(得分:0)

请尝试使用此,在此引荐中,可以调用 .map()函数的集合。 map()函数包含2个参数。第一个:集合中的项目,第二个:索引。索引可用作键,以按键创建唯一元素。

<select>
this.state.referti.map(function(item, index){  
  return <option key={index}>{item}</option>
})
</select>