【问题标题】:My code is showing error when search is not found with React使用 React 找不到搜索时,我的代码显示错误
【发布时间】:2020-08-19 01:00:00
【问题描述】:

请对使用 API 的 React 不熟悉,当找不到搜索对象时,它会返回错误!请帮我。 我尝试过使用我知道的技术,但它不起作用。 我需要做什么或添加什么以使其工作并在未返回搜索时返回非错误。

function Search() {
const[searchQuery, setSearchQuery] = useState('');
const[advices, setAdvices] = useState({ slips: [] });
const text = 'Tweet';
const shareText = 'Check https://adviser.surg.sh for more...';
const onInputChange = (e) => {
    setSearchQuery(e.target.value);
}

let API_URL = `https://api.adviceslip.com/advice/search/`;

const fetchAdvices = async () => {
    const result = await axios.get(`${API_URL}${searchQuery}`);
    console.log(result.data);
    setAdvices(result.data);
}

const onSubmitHandler = (e) => {
    e.preventDefault();
    fetchAdvices();
}

return (
    <div>
        
        <section>
            <form className='search-box' onSubmit={onSubmitHandler}>
                    <input
                     
                    type='search'
                    placeholder='Search for advice e.g love'
                    value={searchQuery}
                    onChange={onInputChange}
                    />
                    <button className='search-btn' type='submit'>Search</button>
            </form>
            <div className='adviceList'>
                {
                    advices.slips.map((advice, id) => {
                        return (
                            <div key={id}>
                                <div className='advice-card'>
                                    <h2>{advice.advice}</h2>
                                
                                   <p> <Twitter text={text} 
                                        url={advice.advice} 
                                        shareText={shareText} />
                                    </p>
                                </div>
                            </div>
                        );
                    })
                }
            </div>
        </section>

    </div>
)
 }

export default Search

我该如何解决这个问题,请帮助我做什么。

【问题讨论】:

  • 错误是什么?哪一行?

标签: reactjs api


【解决方案1】:

最佳解决方案是让后端返回某种数据,即使未找到结果(例如 found 属性)。然后,使用该数据检查是否有结果。否则,您必须进行错误处理:

const fetchAdvices = async () => {
  try {
    const result = await axios.get(`${API_URL}${searchQuery}`);
    console.log(result.data);
    setAdvices(result.data);
  } catch(e) {
    setAdvices({slips: []}); //or any other value you want to set it to when there's no result returned
  }
    
}

【讨论】:

  • 请问如果没有找到,我该如何返回错误?
  • 如果你的意思是在后端返回什么,基本上只需在后端而不是前端添加一个 try {...} catch(e) {...} 块。对于返回的结果,您可以执行 data = {found: true, result: 'whatever result it is'}data = {found: false, result: undefined} 之类的操作
  • 我真的不明白这一点。但是我说的是返回结果时的前端。如果找到结果,则显示结果。现在如果没有找到结果,这意味着现在是错误我将如何在前端显示它,请看一下我的代码的后面部分。感谢reipies,非常感谢。
  • 谢谢!如果没有找到结果,它会响应,但问题是如果找到结果它会抛出这个错误 Unhandled Rejection (TypeError): result.data.message is undefined 我该如何解决呢!
【解决方案2】:

不要使用await,试试这个;

const fetchAdvices = axios.get(`${API_URL}${searchQuery}`)
    .then(result => {
        console.log(result.data);
        setAdvices(result.data);
    }).catch(error => {
        console.log(error);
        // handleError(error);
    });
       

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2017-04-03
    相关资源
    最近更新 更多