Reactjs 反应:当新搜索没有结果时,如何清除以前的结果

Reactjs 反应:当新搜索没有结果时,如何清除以前的结果,reactjs,Reactjs,我想清除以前的搜索结果,如果没有新搜索的结果。目前,我有一个警告框弹出“无结果”消息。我想同时清除以前搜索的结果 我尝试在else语句中将此.setState({contracts:{}})添加为空,但由于SearchResults组件无法再读取constracts状态,它会使站点崩溃 我还尝试在没有结果的情况下将SearchResults组件的显示更改为null,但这必须要起作用 如果没有结果,是否有方法将contracts状态添加到componentWillUnmount 搜索结果组件 co

我想清除以前的搜索结果,如果没有新搜索的结果。目前,我有一个警告框弹出“无结果”消息。我想同时清除以前搜索的结果

我尝试在else语句中将此.setState({contracts:{}})添加为空,但由于SearchResults组件无法再读取constracts状态,它会使站点崩溃

我还尝试在没有结果的情况下将SearchResults组件的显示更改为null,但这必须要起作用

如果没有结果,是否有方法将contracts状态添加到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}
    />
const SearchResults=props=>(
{console.log(props)}
搜索结果
{props.labels.map(label=>({label.DisplayName}))}
{props.contracts.map((contract,i)=>(
{props.handleContract(contract.Fields.filter(field=>field.DataField==“IDXT001”).map(field=>field.DataValue))}
className=“可单击行”
target=“\u blank”
>
{contract.Fields.map(docs=>
{docs.DataValue}}
))}
)
搜索表单组件

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}
    />
类SearchForm扩展了React.Component{
构造函数(…参数){
超级(…args);
this.state={
莫达尔肖:错,
};
}
render(){
报税表(
{this.props.labels.map(label=>(
  • {label.DisplayName}:
  • { this.props.handleInputChange(label.DataField,e.target.value)} value={this.props.newFormValues} maxLength=“999” 样式={{高度:34}} name=“value” type=“搜索” className={“表单控件mb-2 mr-sm-2”} id={label.DataField} />
))} 搜寻 重置
父组件

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}
    />
class SearchPage扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
标签:[],
合同:[],
formValues:{},
PDF:[],
标题:[],
秀:假,,
};
this.onClick=this.handleContract.bind(this);
this.handleShow=this.handleShow.bind(this);
this.handleClose=this.handleClose.bind(this);
}
initialState={
formValues:{},
}
componentDidMount(){
这是loadLabels();
}
handleFormReset=()=>{
this.setState(()=>this.initialState)
log(“值为”+JSON.stringify(this.state.formValues))
}
handleClose(){
this.setState({show:false});
}
handleShow(){
this.setState({show:true});
}
loadLabels=()=>{
API.getLabels()
。然后(res=>{
常量标签=分辨率数据;
console.log(标签)
this.setState({labels})
})
.catch(err=>console.log(err));
};
handleInputChange=(键,值)=>{
const newFormValues=Object.assign({},this.state.formValues,{[key]:value});
this.setState({formValues:newFormValues})
};
handleContract=(id)=>{
API.openRow(id)
。然后(res=>{
常数pdfs=分辨率数据;
this.setState({pdfs});
这个。道具。历史。推({
状态:{labels:this.state.labels,
pdfs:this.state.pdfs,
标题:this.state.titles}
})
})
.catch(err=>console.log(err));
API.标题(id)
。然后(res=>{
常量标题=资源数据;
this.setState({titles});
})
this.setState({show:true});
}
loadContracts=(查询)=>{
API.search(查询)
。然后(res=>{
const contracts=res.data;
如果(合同长度>0)
this.setState({contracts});
其他的
返回警报(“无结果”)
此.handleFormReset();
})
.catch(err=>console.log(err));
};
handleFormSubmit=事件=>{
event.preventDefault();
const formData=this.state.formValues
让query='';
让keys=Object.keys(formData);
keys.map(k=>{
如果(查询!==“”)
查询+=`&`;
查询+=`过滤器=`
query+=`${k}|${formData[k]}`
这是loadContracts(查询);
})
};


很难说没有看到组件崩溃,但是在
案例中将
契约设置为空数组可能会阻止组件崩溃


this.setState({contracts:[]})

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

不清楚组件的结构和状态处理方式。能否添加更多信息?向问题添加了更多代码这是正确的格式吗?否则返回警报(“无结果”)this.setState({contracts:[]})这样就根本无法显示结果。即使有搜索结果。我认为
This.handleFormReset();
正在将状态设置回空结果,即使有搜索结果。This.handleFormReset()的;将formValues状态重置为空。这将清除下一次搜索的输入。确定。如果我替换了警报框,它将正常工作。使用此.setState({contracts:[])).我有个大脑屁。我怎么能用这个语句得到警报?我要把它添加到我的else语句中吗?我在那里添加了它,但以前的结果仍然存在。是的。你必须放入else块。你添加了这个.setState({contracts:[])吗?是的,我让它工作了