簡體   English   中英

我如何在 react.js 中搜索失敗時返回錯誤消息

[英]How would I return an error message upon a failed search in react.js

我目前正在學習如何在react.jsreact.js網頁的前端代碼,為了完成作業,當用戶在搜索欄中輸入任何不在我的database內容時,我需要返回一條消息說找不到 Campground .

例如:

如果他們輸入Banana而不是真正的campground name ,則需要顯示消息。 我確信這相對簡單,我現在完全不知所措。

下面是我的find.js文件的代碼:

import Layout from '../components/MyLayout.js';
import React from "react";
import {getInfo} from '../lib/utils.js';

class Find extends React.Component {
  constructor(props) {
    super(props);
    this.state={search: ""};
  }

  handleUpdate(evt){
    this.setState({search: evt.target.value});
  }

  async handleSearch(evt){
    const park = await getInfo(this.state.search);
    this.setState({park});
  }

render() {
  return (
    <Layout>
    <div style={{ margin: "auto auto", width: "600px", textAlign: "center" }}>
        <h1>New Mexico Camground Search</h1>
        <p><input type='text' value={this.state.search} onChange={this.handleUpdate.bind(this)}/></p>
        <div className="button-style" onClick={this.handleSearch.bind(this)}>Submit</div>
        {this.state.park ? <div>
        <br />
        <h3>{this.state.park.name}</h3> 
            <br /><img style={{maxWidth: '400px', maxHeight: "400px"}}
            src={this.state.park.image_url} /> <br />
            <h3>{this.state.park.closest_town}</h3>
            <p>{this.state.park.description} </p>
          </div> : null}
      <style jsx>{`
        h1,
        a {
          font-family: 'Sans';
          color: #ffa500;
        }
        h2,
        a {
            font-family: 'Sans'
            color: #ffa500;
        }
        .button-style {
            margin: auto auto;
            cursor: pointer;
            background-color: #ffa500;
            color: #ffffff;
            width: 100px;
            font-family: "Sans";
        }
        ul {
          padding: 10;
        }
        li {
          list-style: none;
          margin: 5px 0;
        }
        a {
          text-decoration: none;
          color: blue;
        }
        a:hover {
          opacity: 0.6;
        }
      `}</style>
      </div>
    </Layout>
      )
  }
    }
}

export default Find;

你可以用try/catch來做

async handleSearch(evt) {
  try { 
    const park = await getInfo(evt.target.value);
    this.setState({park});
  } catch(error) {
    // do something with error
  }
}

(也可以直接使用目標值)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM