首页 > 解决方案 > 不处理缺失的细节,响应 False

问题描述

当标题不存在时,如何检查是否发出警报?

这可以用axios实现吗?

在此处输入图像描述

export const getMoviesImdb = async (title) => {
  title = encodeURIComponent(title);
  return fetch(`http://www.omdbapi.com/?s=${title}`)
  .then((response) => response.json()
      .then((data) => {
        if (data.Response != "False") {
          return data.Search
        }
        return Promise.reject(data.Message);
      }, [])
      .catch((error) => {
        return Promise.reject(error); 
      })
  );
};

标签: reactjsajaxaxios

解决方案


使用 axios,您可以使用response.data. 此外,它已经返回了一个 Promise,因此您不必显式地返回 Promise。而是检查 api 响应并抛出错误,然后在使用中(调用getMoviesImdb函数的地方)简单地捕获它。最后,getMoviesImdb乐趣不必是异步的乐趣。

工作演示(只需在 url 中添加您的 api 密钥进行测试)

代码片段示例

export default function App() {
  useEffect(() => {
    let myMovies;
    getMoviesImdb("asdf")
      .then(res => {
        // make sure to use your api key to see results
        console.log("res", res);
        myMovies = res;
      })
      .catch(err => {
        // make sure to use your api key to see error message
        console.log("err", err);
      });
  }, []);

  const getMoviesImdb = title => {
    console.log("title", title);
    // title = encodeURIComponent(title);
    // use your api key below
    return axios(`http://www.omdbapi.com/?s=${title}`).then(response => {
      // console.log("response", response);
      if (response.data.Response !== "False") {
        return data.Search;
      }
      console.log("response.data", response.data.Error);
      throw new Error(response.data.Error);
    });
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}


推荐阅读