在react js的if else条件中获取错误

时间:2019-02-12 09:15:01

标签: reactjs

我是React JS的新手,我想在分页中使用else条件,但是当我应用该条件时出现错误,在这里我添加了条件{ (this.state.value>0) ? },在这里添加了我的整个代码,任何人都可以帮助我如何应用该条件

class Permits extends React.Component {
  constructor(props){
    super(props);

    //this.onImportPermitClick = this.onImportPermitClick.bind(this);

    this.state = {
      options:{},
      results:[],
      total : 0,
    };
    autobind(this);
  }

  componentWillReceiveProps(np){

  }

  componentDidMount(){
    // query options - region, locality, type, key type
    this.props.request('permit-search-options.php', {}, function(r){
      if(r.ok){
        this.setState({options: r.msg});
      }
    }.bind(this));
  }
  startDateChange(d){
    this.setState({startDate: moment(d).format("YYYY-MM-DD HH:mm:ss")});
  }
  endDateChange(d, other){
    this.setState({endDate: moment(d).format("YYYY-MM-DD HH:mm:ss")});
  }
  onSearchClick(){
    l('search was clicked');
    //alert('sdsds');        

    // gather data - request to permit-search, display below
    var data = pluck(this.state, 'region', 'search', 'locality', 'key_type', 'type', 'endDate', 'startDate');
    // format dates into strings
    if(isset(data.startDate)){
      data.start_date = moment(data.startDate).format("YYYY-MM-DD HH:mm:ss");
    }
    if(isset(data.endDate)){
      data.end_date = moment(data.endDate).format("YYYY-MM-DD HH:mm:ss");
    }
    l('data is', data);
    // ajax - request for search
    this.props.request('permit-search.php', data, function(r){
      if(!r.ok){
        toastr.error("oops, something went wrong");
      }else{
        this.setState({results:r.msg,total:r.total});
      }
    }.bind(this));
  }
    onImportPermitClick() {
        jQuery(".modal-title").text('Import Permit');  
        jQuery(".modal-body").html('<form class="form-horizontal" action="" method="post" name="upload_csv_permit" id="upload_csv_permit" onsubmit="return false;" enctype="multipart/form-data"><input type="hidden" id="actio_url" value="Permity::saveImportCsvFile"><div class="form-group"><label for="email">Import CSV File:</label><input type="file" class="form-control" id="permit_csv_file"></div>  </form>');
        jQuery("#import_permit_modal").modal('show');
    }         

  render(){
    var toggle_checks = function(){
      var on = !dflt(this.state.results[0], {selected:false}).selected;
      var results = this.state.results.map(function(val, ndx){
        val.selected = on;
        return val;
      });
      this.setState({results: results,total:total});
    }.bind(this);

    //alert(this.state.total);

    var add_to_print = function(){
      // ajax this to print_qs
      var records = this.state.results.reduce(function(curr, val){
        if(val.selected){
          curr.push(val.id);
        }
        return curr;
      }, []);

      this.props.request('add-to-print-cart.php', {records:records, record_type:0}, function(r){
        if(!r.ok){
          toastr.error("oops, something went wrong");
        }else{
          toastr.success(r.msg);
        }
      }.bind(this));
    }.bind(this);
    return (
        <div className="permits pt-4">
          <div className='form-group row'>
            <div className="col-md-8 col-md-offset-2">
              <Input name="search" label="Search" value={this.state.search}
                onChange={onChange.bind(this)} placeholder='Search...' />
            </div>
            <div className="col-md-12"></div>
            <div className="col-md-3">  
              <Select name="region" onChange={onChange.bind(this)} value={this.state.region}
                options={this.state.options.regions} label="Region"></Select>
            </div>
            <div className="col-md-3">
              <Select name="locality" onChange={onChange.bind(this)} value={this.state.locality}
                options={this.state.options.localities} label="Locality"></Select>
            </div>
            <div className="col-md-3">
              <Select name="key_type" onChange={onChange.bind(this)} value={this.state.key_type}
                options={dflt(this.state.options.key_types, []).map(function(val){ return val.val; })} label="Key Type"></Select>
            </div>
            <div className="col-md-3">
              <Select name="type" onChange={onChange.bind(this)} value={this.state.type}
                options={this.state.options.project_types} label="Type"></Select>
            </div>
            <div className="col-md-4">
              <label htmlFor="from">Start Date</label> <br/>
              <DatePicker
                  selected={isset(this.state.startDate)?new Date(this.state.startDate):null}
                  onChange={this.startDateChange}
                  maxDate={isset(this.state.endDate)?new Date(this.state.endDate):null}
                  placeholderText="From..."
                />
            </div>
            <div className="col-md-4">
              <label htmlFor="from">End Date</label> <br/>
              <DatePicker
                  selected={isset(this.state.endDate)?new Date(this.state.endDate):null}
                  onChange={this.endDateChange}
                  minDate={isset(this.state.startDate)?new Date(this.state.startDate):null}
                  placeholderText="To..."
                />
            </div>
            <div className="col-md-4">
              <Select name="order_by" onChange={onChange.bind(this)}
                value={this.state.order_by} label="Report By"
                options={[
                  {id:'localities.name', name:'Locality'},
                  {id:'permit_no', name:'Permit #'},
                  {id:'project_types.name', name:'Type'},
                  {id:'issue_date', name:'Date'},
                  {id:'owner_name', name:'Owner'},
                  {id:'contractor_name', name:'Contractor'},
                  {id:'mla_name', name:'MLA'},
                  {id:'jobvalue', name:'Value $'}
                ]} />
            </div>
          </div>
          <div className="row mb-4">
            <div className="col-md-6 col-md-offset-3">
              <div className="btn btn-primary btn-lg mt-2" onClick={this.onSearchClick}
                style={{width:'100%'}}>Search</div>
            </div>
          </div>

          <div className="row mb-4">
            <div className="col-md-6 col-md-offset-3">
              <div className="btn btn-primary btn-lg mt-2" onClick={this.onImportPermitClick}
                style={{width:'100%'}}>Import Permit</div>
            </div>
          </div>

          <div className="row mt-4 permit-results">
            <div className="col-xs-6">
              <div className="btn btn-default btn-md" onClick={toggle_checks}
                >Toggle All</div>
            </div>
            <div className="col-xs-6 text-right">
              <div className="btn btn-success btn-md float-right" onClick={add_to_print}
                ><i className="fas fa-plus"></i> Add to Print Cart</div>
            </div>
            <div className="col-xs-12 p-2">
              <Table striped bordered hover>
                <thead>
                  <tr>
                    <th>Select</th>
                    <th>Id</th>
                    <th>Value</th>
                    <th>Issue Date</th>
                    <th>Owner</th>
                    <th>Contractor</th>
                    <th>Claimant</th>
                    <th>Key Type</th>
                    <th>Description</th>
                    <th>Site Address</th>
                    <th>Legal Description</th>
                    <th>Comments</th>
                  </tr>
                </thead>
                <tbody>
                  {this.state.results.map(function(val, ndx){
                    // l('row-', val);
                    var onClick = function(e){
                      var results = this.state.results;
                      var result = results[ndx];
                      results[ndx].selected = !(val.selected);
                      this.setState({results:results});
                    }.bind(this)
                    return <tr className="item" onClick={onClick} key={ndx}>
                            <td> <i className={"far " + (val.selected?'fa-check-square-o':'fa-square-o')}></i> </td>
                            <td className="permit_no">{val.permit_no}</td>
                            <td className="job_value">${val.jobvalue}</td>
                            <td className="issue_date">{val.issue_date}</td>
                            <td className="owner_info">
                              {['name', 'address','city', 'state', 'zip', 'phone'].reduce(function(curr, vndx){
                                var v = val['owner_' + vndx];
                                if(!blank(v)){
                                  curr += v + " \n";
                                }
                                return curr;
                              }, '')}
                            </td>
                            <td className="contractor_info">
                              {['name', 'address','city', 'state', 'zip', 'phone'].reduce(function(curr, vndx){
                                var v = val['contractor_' + vndx];
                                if(!blank(v)){
                                  curr += v + " \n";
                                }
                                return curr;
                              }, '')}
                            </td>
                            <td className="contractor_info">
                              {['name', 'address','city', 'state', 'zip', 'phone'].reduce(function(curr, vndx){
                                var v = val['mla_' + vndx];
                                if(!blank(v)){
                                  curr += v + " \n";
                                }
                                return curr;
                              }, '')}
                            </td>
                            <td>{val.key_type}</td>
                            <td>{val.description}</td>
                            <td>{val.street}</td>
                            <td>{val.subdivision}</td>
                            <td>{val.comments}</td>
                          </tr>;
                  }.bind(this))}
                </tbody>
              </Table>
            </div>


                { (this.state.value>0) ? }  
                 <div className="col-xs-12 pull-right">
                            <Pagination>
                              <Pagination.First />
                              <Pagination.Prev />
                              <Pagination.Item>{1}</Pagination.Item>
                              <Pagination.Ellipsis />

                              <Pagination.Item>{10}</Pagination.Item>
                              <Pagination.Item>{11}</Pagination.Item>
                              <Pagination.Item active>{12}</Pagination.Item>
                              <Pagination.Item>{13}</Pagination.Item>
                              <Pagination.Item disabled>{14}</Pagination.Item>

                              <Pagination.Ellipsis />
                              <Pagination.Item>{20}</Pagination.Item>
                              <Pagination.Next />
                              <Pagination.Last />         
                            </Pagination>  
                      </div>     



          </div>
        </div>
    )

  }
}


export default Permits;

1 个答案:

答案 0 :(得分:1)

如果您想添加条件以进行反应,请使用以下语法:

   render () {
     return (
       <div>
         {this.state.condition
         ? (<div>positive</div>)
         : (<div>negative</div>)}
       </div>
     )
   }

您的代码虽然有很多反模式,例如: 在渲染器内部使用setState,在渲染器内部定义函数等等,这可能会导致性能问题。 还可以考虑使用es6编写代码。它比绑定每个函数更清晰,更易读,您只需使用箭头自绑定函数语法