繁体   English   中英

如何解决反应项目中显示的此错误 - 未捕获(承诺)TypeError:无法读取未定义的属性(读取'id')

[英]How to solve this error showing in react project - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')

import React ,{useEffect, useState}from 'react'

import Layout from '../components/Layout'

import axios from 'axios';

import TinderCard from 'react-tinder-card'

import MovieCard from '../components/MovieCard';

import { createClient } from '@supabase/supabase-js'

import { useAuth } from '../auth';


function Home() {

  const auth = useAuth();
  const supabaseUrl = process.env.REACT_APP_SUPABASE_URL
  const supabaseKey = process.env.REACT_APP_SUPABASE_KEY
  const supabase = createClient(supabaseUrl, supabaseKey)
  const [movies, setMovies] = useState([])
  const [message, setMessage] = useState("")
  
 const fecthMovies = async () => {
  const {data} = await axios.get("https://api.themoviedb.org/3/discover/movie",{
    params:{
      page:Math.random() * 501,
      api_key:"57e19e5c44a33653ce6bfc54743c9e2e"
    }
  })
 console.log(data);
const movie = await data;
setMovies(movie.results);
}
const addTowatchlist = async (movie) => {

const {data, error} = await supabase.from("watchlists").insert({movie_id : movie.id, user_id: auth.user.id})
if(error){
  console.log(error)
}
if(data){
  setMessage("Movie has been added to your watchlist")
}
}

 useEffect(() => {
  if(auth.user){
    fecthMovies()
  }
  
 
 },[auth])





return (
  <Layout>
    {message&&message}
    <h1>Welcome</h1>
    {!auth.user && <h2>Please sign up</h2>}

{movies.map(movie => {
 return <>
 <div className="movie-wrapper">
 <TinderCard
 onSwipe={direction => direction === "right"? addTowatchlist():null}
 key={movie.id}>
    <MovieCard movie={movie}/>
  
  </TinderCard>
 </div>
 
 </>
})}

  </Layout>
 )
 

}

export default Home

这是错误

上面给出的是我的 Home.js。 我不知道为什么它显示未定义。 我试图将 'movies.map' 中的 'movies' 更改为 'Movies' 等等,但它并没有做那么多。 当我尝试将项目添加到我在 supabase 数据库中创建的监视列表表时,会发生此错误。 我需要将从项目中获取的电影“id”添加到监视列表表中。 当我尝试这个

const {data, error} = await supabase.from("watchlists").insert({movie_id : movie?.id, user_id: auth.user.id})

喜欢添加? 在“movie.id”中它有效但我没有得到 id 因为? . 那么如何通过修复此错误将电影 ID 添加到列表中。 非常感谢您的帮助。 提前致谢。

这?。 算子就好了。 链接运算符,除了如果引用为空(null 或 undefined)时不会导致错误,表达式会短路并返回 undefined 值。 当与 function 调用一起使用时,如果给定的 function 不存在,它将返回未定义。

所以在下面的代码中 user_id: auth?.user?.id 直到它为 nullish 时才可以访问它,如果它是 null 它将返回 undefined 而不是使应用程序崩溃。

const {data, error} = await supabase.from("watchlists").insert({movie_id : movie?.id, user_id: auth?.user?.id})

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM