React:当没有结果的新搜索时如何清除以前的结果

时间:2019-04-05 13:09:52

标签: reactjs

我希望清除以前的搜索结果,如果没有新搜索的结果。当前,我弹出一个警告框,显示“无结果”消息。我想同时清除上一次搜索的结果。

我尝试在else语句中将此this.setState({contracts:{}})添加为空,但是由于SearchResults组件无法再读取合同状态,因此该网站崩溃了。

如果没有结果,我还尝试将SearchResults组件的显示更改为null,但这完全可以生效。

如果没有结果,是否可以将合同状态添加到componentWillUnmount?

搜索结果组件。

const SearchResults = props => (

  <div>{console.log(props)}
    <div>
       </div>   
       <div>
    <div className="row" ><h4 style={{margin:"auto", marginBottom:"15px"}}>Search Results</h4></div>
    <table className="table table-striped">
      <thead>
        <tr>
          {props.labels.map(label => ( <th key={label.Id}>{label.DisplayName}</th>))}
        </tr>
      </thead>
      <tbody>

{ props.contracts.map((contract, i) => (

    <tr key={i} data-id={contract.Id}  
        onClick={(e) => {props.handleContract(contract.Fields.filter(field => field.DataField === "IDXT001").map(field => field.DataValue))}}
        className="clickable-row"
        target="_blank"
        >
        {contract.Fields.map( docs =>  
        <td key={docs.Id}><span id={docs.DataField}>{docs.DataValue}</span></td>)}
    </tr>))}

      </tbody>
    </table>
    </div>
</div>
)

搜索表单组件。

  class SearchForm extends React.Component {

    constructor(...args) {
      super(...args);

      this.state = { 
        modalShow: false,
      };
    }

    render() {

      return ( 
<form className="form-inline col-md-12" onReset={this.props.handleFormReset}>

{this.props.labels.map(label => (
  <div className="card border-0 mx-auto" style={styles} key={label.Id}>
       <ul className="list-inline ">
          <span>
            <li>
              <Labels  htmlFor={label.DisplayName} >{label.DisplayName}:</Labels>
            </li>
            <li >
              <Input  
                key={label.Id}
                onChange={(e) => {
                  this.props.handleInputChange(label.DataField, e.target.value)}}
                value={this.props.newFormValues}
                maxLength="999"
                style={{height:34}}
                name="value"
                type="search" 
                className={"form-control mb-2 mr-sm-2"} 
                id={label.DataField}
              />
            </li> 
          </span>
      </ul>
  </div>
))}

  <div className=" col-sm-12">

  <Button
        style={{ float: "left", marginBottom: 10 }} 
        className="btn btn-success"
        type="submit"
        onClick={this.props.handleFormSubmit}
      >
        Search
      </Button>

      <Help />

      <Button
        style={{ float: "left", marginBottom: 10 }} 
        className="btn btn-secondary"
        type="reset"
        onClick={this.props.handleFormReset}
      >
        Reset
      </Button>

父组件。

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


      this.state = {
        labels: [],
        contracts: [],
        formValues:{},
        pdfs:[],
        titles:[],
        show: false,

      };
      this.onClick = this.handleContract.bind(this);
      this.handleShow = this.handleShow.bind(this);
      this.handleClose = this.handleClose.bind(this);

    }

    initialState = { 
      formValues: {},
    }

    componentDidMount(){
      this.loadLabels();
    }


    handleFormReset = () => {
      this.setState(() => this.initialState)
      console.log("value is"+JSON.stringify(this.state.formValues))

    }

    handleClose() {
      this.setState({ show: false });
    }

    handleShow() {
      this.setState({ show: true });
    }

    loadLabels = () => {
      API.getLabels()
        .then(res => {
          const labels = res.data;
          console.log(labels)
            this.setState({ labels })
        })
        .catch(err => console.log(err));
    };

    handleInputChange = (key, value) => {
       const newFormValues = Object.assign({}, this.state.formValues, {[key]: value});
     this.setState({ formValues: newFormValues })
    };

    handleContract = (id) => {
      API.openRow(id)
      .then(res => {
        const pdfs = res.data;
        this.setState({pdfs});
        this.props.history.push({
          state: { labels:this.state.labels,
            pdfs:this.state.pdfs,
            titles:this.state.titles }
        })
      })
      .catch(err => console.log(err));
      API.titles(id)
      .then(res => {
        const titles = res.data;
        this.setState({titles});
      })
      this.setState({ show: true });
    }

  loadContracts = (query) => {
    API.search(query)
    .then(res => {
      const contracts = res.data;
      if (contracts.length > 0 )
      this.setState({ contracts });
      else
         return alert("No results")
      this.handleFormReset();
    })
    .catch(err => console.log(err));
    };


    handleFormSubmit = event => {  
    event.preventDefault();
    const formData = this.state.formValues
    let query = '';
    let keys = Object.keys(formData);
    keys.map(k => { 
      if (query !== "")
      query += `&`;
      query += `filter=`
      query += `${k}|${formData[k]}`

      this.loadContracts(query);
     })

    };
  <SearchForm 
    labels={this.state.labels}
    handleFormSubmit={this.handleFormSubmit}
    handleInputChange={this.handleInputChange}
    handleReset={this.handleReset}
    handleFormReset={this.handleFormReset}
    />

    <br/>
  <SearchResults 
    labels={this.state.labels}
    contracts={this.state.contracts} 
    pdfs={this.state.pdfs}
    handleContract={this.onClick}
    handleTitles={this.onClick}
    />

2 个答案:

答案 0 :(得分:0)

不用说会崩溃的组件就可以说,但是在contracts情况下将else设置为空数组可能会防止组件崩溃。

this.setState({contracts:[]})

答案 1 :(得分:0)

假设搜索结果是一个对象数组,则可以将合同设置为空数组,而不是将其设置为空对象。 this.searchResults = []