简体   繁体   English

来自 api 的用户搜索得到错误的过滤响应:`未处理的拒绝(TypeError):无法读取未定义的属性'结果'

[英]Filter response from api on user search getting error :`Unhandled Rejection (TypeError): Cannot read property 'results' of undefined`

Trying to update my state with a filtered api response.尝试使用过滤后的 api 响应更新我的 state。 I make the call and then update the results state (see below).我拨打电话,然后更新results state(见下文)。

api call api 拨打

  async searchMovies(keyword, year) {
    const response = await getMoviesFiltered(keyword, year);
    console.log(response); // filtered response
    this.setState({ results: response.results});
  }

request要求

export const getMoviesFiltered = async (keyword, year) => {
  try {
    const response = await axios.get(
      `https://api.themoviedb.org/3/search/movie?api_key=<apikey>&language=en-US&query=${keyword}&page=1&include_adult=false&year=${year}`
    );
    console.log(response.data.results);
    return response.data;

  } catch (error) {
    console.error(error);
  }
};

response from api:来自 api 的回复:

{page: 1, results: Array(20), total_pages: 95, total_results: 1889}
page: 1
results: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
total_pages: 95
total_results: 1889

I want to update my state with the response (results key, which is an array) and map over it but it tells me that Unhandled Rejection (TypeError): Cannot read property 'results' of undefined which is strange as i can see results in the response我想用响应(结果键,它是一个数组)和 map 更新我的 state 但它告诉我Unhandled Rejection (TypeError): Cannot read property 'results' of undefined这很奇怪,因为我可以看到results响应

Also, when I attempted to update the results in the state with response eg此外,当我尝试使用response更新 state 中的结果时,例如

this.setState({ results: response});

I get:我得到:

TypeError: movies.map is not a function

ie it can't map over the response i am passing down.... I have looked at other questions on stack and they say this is because the response is not an array, but mine is:S即它不能超过我传递的响应 map...。我查看了堆栈上的其他问题,他们说这是因为响应不是数组,但我的是:S

Here is where i am mapping over the data, which is passed down from the parent.这是我映射数据的地方,它是从父级传递下来的。

 <MovieList movies={results || []} genres={genreOptions || []} />

component:零件:

    return (
      <MoviesWrapper>
        {movies && movies.map((movie, index) => {
          const {
            title,
            vote_average,
            overview,
            release_date,
            poster_path,
            genre_ids,
          } = movie;
          return (
            <MovieItem
              key={index}
              title={title}
              rating={vote_average}
              overview={overview}
              release={release_date}
              poster={poster_path}
              movieGenres={matchGenres(genre_ids)}
            />
          );
        })}

can anyone see what is wrong?谁能看出哪里出了问题?

Cant see your full component codes;看不到您的完整组件代码; but the problem is probably that you initialized your state null.但问题可能是您初始化了 state null。

When you have a state defined in your code, the state initializes with its initial value.当您在代码中定义了 state 时,state 将使用其初始值进行初始化。

const [Movies, setMovies] = useState(null)

Now i have defined a state called Movies and its null at the beginning.现在我已经定义了一个名为 Movies 的 state 及其开头的 null。

I do my API call at useEffect block(or ComponentDidMount);我在 useEffect 块(或 ComponentDidMount)调用 API; and after my API response, i update the state to response with setState, or in example above;在我的 API 响应之后,我将 state 更新为使用 setState 响应,或者在上面的示例中; setMovies().设置电影()。

useEffect(() => {
   const response = await axios.get(`ENDPOINT_URL`);
   setMovies(response) 
},[]);

Now my state is the response array from my API call.现在我的 state 是我的 API 调用的响应数组。 Only now I can use map function, not before;只有现在我可以使用 map function,以前不行; because it was null and would throw an error.因为它是 null 并且会抛出错误。

Lets dive into how React handles this flow in return block.让我们深入研究 React 如何在 return 块中处理这个流程。 React does not wait for the API call to end to initialize the state and print what is in return block. React 不会等待 API 调用结束来初始化 state 并打印返回块中的内容。 This is important;这个很重要; because if i try to do something with the state at the first render;因为如果我尝试在第一次渲染时对 state 做些什么; before react updates the state with the response array from api;在 React 使用来自 api 的响应数组更新 state 之前; the state will be "null". state 将为“空”。

So the order is like this.所以顺序是这样的。

1.Initialize state with initial value (null) 1.用初始值(null)初始化state

2.Render return block 2.渲染返回块

3.Update state (Example: setMovies([1,2,3]) ) 3.更新 state (例子: setMovies([1,2,3]) )

4.Re-render return block. 4.重新渲染返回块。

Lets say i have {console.log(Movies)} in my return block.可以说我的返回块中有 {console.log(Movies)} 。 I will see 2 logs in the console;我将在控制台中看到 2 个日志; the first one will say "null"(step 2), and the second one will say "[1,2,3]" (step 4)第一个会说“null”(第 2 步),第二个会说“[1,2,3]”(第 4 步)

Now, if i have Movies.map function inside return block;现在,如果我在返回块中有 Movies.map function; it will throw an error which will say "TypeError: Movies.map is not a function";它会抛出一个错误,说“TypeError: Movies.map is not a function”; because Movies is null at the first.因为 Movies 首先是 null。

As for your other question: "Unhandled Rejection (TypeError): Cannot read property 'results' of undefined"至于你的其他问题:“未处理的拒绝(类型错误):无法读取未定义的属性‘结果’”

This error is thrown when parent object is empty;当parent object为空时抛出该错误; in this case;在这种情况下; parent object of results.结果的父 object。 Cant be sure which "results" is throwing error here because you didnt provide row number of exact error.无法确定是哪个“结果”在此处引发错误,因为您没有提供确切错误的行号。 For example;例如; data.results is throwing this; data.results 正在抛出这个; it means "data" is empty and does not have results as child object. This is most likely result of 2 things;这意味着“数据”是空的,并且没有作为孩子 object 的结果。这很可能是两件事的结果; when we judge response object schema wrong, (Ex: response.data.movies.results instead of response.data.results) or we tried to reach data.results before we fill it "Ex: data = apiresponse.content".当我们判断响应 object 架构错误时,(例如:response.data.movies.results 而不是 response.data.results)或者我们在填充它之前尝试到达 data.results “Ex:data = apiresponse.content”。

If you can provide a CodeSandbox;如果你能提供一个CodeSandbox; it would be much easier to answer.回答起来会容易得多。

Edit after codesandbox在codeandbox之后编辑

Error corrected: https://codesandbox.io/s/movies-app-angela-forked-ehr9u更正错误: https://codesandbox.io/s/movies-app-angela-forked-ehr9u

Errors:错误:

  • MovieList where you.map movies;你所在的电影列表.map 部电影; the state initializes empty because of the reasons i explained above;由于我上面解释的原因,state 初始化为空; so it throws error;所以它会抛出错误; You can just add {movies && movies.length > 0...} 1 step above map function to check if movies exists and isnt empty.您只需在 map function 上方添加 {movies && movies.length > 0...} 1 步即可检查电影是否存在且不为空。

  • In your searchMovies function your fetcher call catches errors but only console.logs;在您的 searchMovies function 中,您的 fetcher 调用捕获了错误,但仅捕获了 console.logs; this creates problem in searchMovies function. Because even if the response is null or errorcode, searchMovies function still continues to work, and updates the state wrongly.这会在 searchMovies function 中产生问题。因为即使响应是 null 或错误代码,searchMovies function 仍会继续工作,并错误地更新 state。

  • Your search doesnt show responses in view;您的搜索没有在视图中显示响应; because after the call in searchMovies;因为在 searchMovies 中调用之后; you need to provide a direct access to results object array so view knows types.您需要提供对结果 object 数组的直接访问,以便视图知道类型。 MoviesList component knows and renders array of movie objects; MoviesList 组件知道并呈现电影对象数组; but after searching you set the state to the object also containing different properties;但是在搜索之后,您将 state 设置为 object 也包含不同的属性; so MoviesList doesnt know how to render results.所以 MoviesList 不知道如何呈现结果。 Shortly;不久; response.data.results instead of response.data. response.data.results 而不是 response.data。

  • Your searchBar component, it doesnt actually search exact key press, but 1 before.您的 searchBar 组件,它实际上并不搜索确切的按键,而是搜索之前的 1 个。 Like when you try searching "dark";就像您尝试搜索“黑暗”一样; it searches for "dar".它搜索“dar”。 When you search for "d" it searches for empty string.当您搜索“d”时,它会搜索空字符串。 You have to type "dark" plus 1 space to actually search for "dark".您必须键入“dark”加 1 个空格才能实际搜索“dark”。 So, api returns 422 Unprocessable entry error at first character you type because it tries to search for empty string.因此,api 在您键入的第一个字符处返回 422 无法处理的输入错误,因为它试图搜索空字符串。 Its because you update the state, then call search api. But updating state is asynchronous, and state updating doesnt finish before you send state to api fetcher function. So simple solution to this would be sending search fetcher function event.target.value, instead of the state you are updating. Its because you update the state, then call search api. But updating state is asynchronous, and state updating doesnt finish before you send state to api fetcher function. So simple solution to this would be sending search fetcher function event.target.value, instead您正在更新的 state。

A small reminder: Change your API key now;一个小提醒:立即更改您的 API 密钥; as its exposed to web.因为它暴露于 web。

Solved the issue.解决了这个问题。

It was to do with the searchMovies api call, when i returned the api response, I have to do a check to see if there is actually a response first of all.这与searchMovies api 调用有关,当我返回 api 响应时,我必须首先检查是否确实有响应。 If there is a response then I want to access the results array in that response.如果有响应,那么我想访问该响应中的results数组。

Essentially do this when setting the state:基本上在设置 state 时执行此操作:

this.setState({ results: response && response.results });

instead of:代替:

this.setState({ results: response.results });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React API错误(未处理的拒绝(TypeError):无法读取未定义的属性“ 0”) - React API Error (Unhandled Rejection (TypeError): Cannot read property '0' of undefined) 未处理的拒绝(TypeError):无法读取未定义的属性 - Unhandled Rejection (TypeError): Cannot read property of undefined axios:未处理的拒绝(TypeError):无法读取未定义的属性“错误” - axios: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined React - 未处理的拒绝(TypeError):无法读取未定义的属性“错误” - React - Unhandled Rejection (TypeError): Cannot read property 'error' of undefined 错误:未处理的拒绝(TypeError):无法读取未定义的属性“livres”,ReactJS,搜索 - Error: Unhandled Rejection (TypeError): Cannot read property 'livres' of undefined, ReactJS, Search 我正在尝试调度一个操作,但收到此错误:“未处理的拒绝(TypeError):无法读取未定义的属性'类型'” - I am trying to dispatch a action but getting this error: “ Unhandled Rejection (TypeError): Cannot read property 'type' of undefined” 为什么在移动对象后出现未处理的拒绝 (TypeError) 错误:无法读取 Redux 应用程序中未定义的属性“过滤器”? - Why after moving the object I have an Unhandled Rejection (TypeError) error: Cannot read property 'filter' of undefined in Redux app? 未处理的拒绝(TypeError):无法读取未定义的属性“子级” - Unhandled Rejection (TypeError): Cannot read property 'children' of undefined React-未处理的拒绝(TypeError):无法读取未定义的属性“ city” - React- Unhandled Rejection (TypeError): Cannot read property 'city' of undefined 未处理的拒绝(TypeError):无法读取未定义的 Stripe Javascript 的属性“id” - Unhandled Rejection (TypeError): Cannot read property 'id' of undefined Stripe Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM