函数在React / Redux

时间:2018-07-03 22:00:55

标签: javascript reactjs

当有人选择啤酒名称时,我试图弹出相应啤酒厂的名称。在filterSearch函数中,如果不将其包装在div中,则可以弹出该名称。我一插入JSX,它就会返回[object Object]。我最终希望返回包含各种信息的卡片,但现在,我正在一步步走。

任何帮助将不胜感激!

 import React, { Component } from 'react';
 import { connect } from 'react-redux';
 import { fetchBeerData } from '../../store/store';
 import { bindActionCreators } from 'redux';
// import { Cards } from '../Cards/Cards';
 
 class PopulateDropdowns extends Component {
 
   state = {
     beerData: []
   }
   
   initialized = false;
 
   componentWillReceiveProps(nextProps){
     if(!this.initialized){
       this.initialized = true;
       this.setState({
        beerData: nextProps.beerData
       })
     }
   }
 
   componentWillMount(){
     this.props.fetchBeerData();
   }
 
   populateSelectLists = () => {
    let brewArr = this.state.beerData
    .sort((a, b) => a[this.props.dataName].localeCompare(b[this.props.dataName]))
    .filter((data, index, self) =>
      index === self.findIndex((d) => (
      d[this.props.dataName] === data[this.props.dataName]
      ))
    )
    let newBrewArr = brewArr.map((e, index) =>
       <option key={index}> {e[this.props.dataName]} </option>
    )

    return(
      this.props.dataName==='Brewery Name'
      ? 
      <form>
        <div className="form-group">
          <label htmlFor="exampleFormControlSelect1">{this.props.label}</label>
            <select className="form-control" id="brew-form-select">
             {newBrewArr}
            </select>
          </div>
      </form>
      :
      <form>
      <div className="form-group">
        <label htmlFor="exampleFormControlSelect1">{this.props.label}</label>
          <select className="form-control" id="beer-form-select">
           {newBrewArr}
          </select>
        </div>
    </form>
    )
  }

  handleSubmit = (e) => {
    e.preventDefault();
    document.getElementById('cardDiv').append(this.filterSearch())
  }

  filterSearch = () => {
    let brewArr = this.state.beerData
    let brewMap = brewArr.filter(this.checkValue).map((res, index) => {   
      return(
        <div key={index}>
          {res['Brewery Name']}
        </div>
      )    
    })
    return (brewMap)
  }

  checkValue = (brew) => {
    return brew['Beer Name'] === this.selectValue()
  }
   
  selectValue = () => {
    let brewVal = document.getElementById('brew-form-select').value
    let beerVal= document.getElementById('beer-form-select').value
    return (this.props.dataName==='Brewery Name' ? brewVal : beerVal)
  }

   render() { 
     return (
       <div id='mainDiv'>
          {this.populateSelectLists()}
          <div className='col-12 text-center' id='cardDiv'></div>
          <button type='submit' onClick={this.handleSubmit}>SUBMIT</button>
       </div>
     )
   }
 }
 
 const mapStateToProps = state => {
   if (state.beerData.length > 0) {
     return {
       beerData: state.beerData
     }
   } else {
     return {};
   }
 };
 
 const mapDispatchToProps = dispatch => {
   return bindActionCreators({ fetchBeerData }, dispatch)
 };
 
 export default connect(mapStateToProps, mapDispatchToProps)(PopulateDropdowns);

1 个答案:

答案 0 :(得分:2)

JSX被编译为一堆React.createElement调用,因此当您执行document.getElementById('cardDiv').append(someJSX)时,它将在DOM中呈现为对象。

您可以在状态中添加一个变量,例如submitted,然后在您的handleSubmit方法中调用this.setState({ submitted: true }),然后在您的render方法中检查submitted是否为true,并渲染您的beerData如果是这样的话。

示例

class PopulateDropdowns extends Component {
  state = {
    beerData: []
  };

  handleSubmit = e => {
    e.preventDefault();
    this.setState({ submitted: true });
  };

  // ... 

  render() {
    return (
      <div id="mainDiv">
        {this.populateSelectLists()}
        <div className="col-12 text-center" id="cardDiv">
          {this.state.submitted &&
            this.state.beerData.filter(this.checkValue).map((res, index) => {
              return <div key={index}>{res["Brewery Name"]}</div>;
            })}
        </div>
        <button type="submit" onClick={this.handleSubmit}>
          SUBMIT
        </button>
      </div>
    );
  }
}