javascript NextJS和React无法读取未定义的属性,并且element.map不是函数

fcipmucu  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(119)

我正在使用NextJS和getServerSideProps从Prisma的数据库中获取一些数据。在开发环境中,我没有遇到任何问题。但在使用vercel部署时,我经常遇到问题。
以下是我所做的:
1.我创建了从数据库获取Toto列表的API路径,在这个函数中,我只返回购物列表数组,如下所示:

import prisma from '../../../lib/prisma'


export default async function handler(req, res) {

    const { userId } = req.query;
    if (req.method === 'GET') {
      try {
        const shoppingLists = await prisma.List.findMany({ where: { userId: userId[0] }});
        res.status(200).send(shoppingLists);
      } 
      catch (error) {
        console.log(error);
        res.status(500).json({ message: 'Something went wrong. Please try again'});  
      }
    }
    else {
      res.status(500).json({message: 'Invalid method requested!'});
    }
}
  1. After this, I created a separate folder called abstraction layer where I do all the DB interactions. I am using axios. In this function I fetch the data and return it as list.data;
// Get all lists
export const getAllLists = async userId => {
    try {
        const lists = await axios.get(`https://next-shopping-list.vercel.app/api/get-all-lists/${userId}`, { 
            headers: { "Accept-Encoding": "gzip,deflate,compress" } // This is taken from internet because I had other errors "invalid file"
        });
        return lists.data;    
    } 
    catch (error) {
        console.log('Abstraction layer error: ', error);
        return 'Something went wrong. Please try again later';
    }
}

//将包含get服务器端props和return()的组件(Dashboard)3.问题来了。我使用SSR是因为我也想保护这个页面。在这个函数中我使用了来自"抽象层"的函数getAllLists,并使用"lists" prop返回购物清单...

export const getServerSideProps = async context => {

  // get sessions with added user Id in the session object
  const session = await requireAuthentication(context);

  // Get all lists
  const shoppingLists = await getAllLists(session?.user.userId);
console.log(shoppingLists);

  if (!session) {
    return {
      redirect: {
        destination: '/signup',
        permanent: false
      }
    }
  }
  
  else {
    return {
      props: {
        newSession: session,
        lists:       shoppingLists
      }
    }
  }
}

1.创建组件后,我开始在尝试Map列表数组时遇到错误,抛出两个错误:

  • The 'props.lists.map()...' is not a function.
  • 无法读取未定义的属性(读取"length")
const Lists = props => {

    const router = useRouter();
    console.log(props.lists);

    const handleDeleteList = async listId => {
        const status = await deleteList(listId);
        console.log(status);      
        if (status.status === 201) {
            router.replace(router.asPath);
        }
    }

    const handleCheckList = async listId => router.push(`/list-items/${listId}`);
 

    // New try re
  return (
    <article>
        {props.lists.length > 0 && props.lists.map(list => (
            <div key={list.id}>
                <div className='flex justify-between my-2 cursor-pointer p-2 items-center'>
                    <p>{ list.title }</p>
                    <div className='flex gap-3'>
                        <AiOutlineDelete size={30} onClick={() => handleDeleteList(list.id)}/>
                        <AiOutlineEye size={30} onClick={() => handleCheckList(list.id)} /> 
                        
                    </div>
                </div>
            </div>
        ))}
    </article>
  )
}

export default Lists

我不明白我做错了什么...在开发环境中,它工作得很完美...

{/* List is empty and display empty message // Else show list */}
        {props.lists && <Lists lists={props.lists}/>}
        {props.lists.length === 0 && 
        <p className="mt-2 text-2xl font-extralight">No lists created yet.</p>}
      </aside>
l7wslrjt

l7wslrjt1#

组件预期props.lists是一个数组,看起来props.list最初没有数组。这就是为什么它会导致错误props.lists.length,并且props.lists.map仅在props.lists是数组时可用。
因此在调用它之前,请确保props.list是一个数组,您可以使用可选的链接(props?.lists.?length

相关问题