在Next.js中将获取的数据作为props传递

inkz8wg9  于 2023-04-05  发布在  其他
关注(0)|答案(1)|浏览(210)

我把代码改成了这个。现在我得到一个错误,说“无法解构'query'的属性'id',因为它是未定义的。”。有人知道为什么吗?我解构了它,但仍然无法到达我传递的元素

'use client';
import { useEffect, useState } from 'react';
import Link from 'next/link';
import axios from 'axios';
import Update from '../update/page';

export default function Read() {
    const [APIData, setAPIData] = useState([]);

    useEffect(() => {
        axios.get('https://64241e5a47401740433376dd.mockapi.io/crudData')
            .then((response) => {
                setAPIData(response.data);
            })
    }, []);


    const getData = () => {
        axios.get('https://64241e5a47401740433376dd.mockapi.io/crudData')
            .then((response) => {
                setAPIData(response.data);
            })
    }

    const onDelete = (id) => {
        axios.delete(`https://64241e5a47401740433376dd.mockapi.io/crudData/${id}`)
            .then(() => {
                getData();
            })
    }

    return (
        <>
            <div className='table_container '>
                <table className="table bg-light rounded-3 table-hover">
                    <thead>
                        <tr className='text-muted'>
                            <th scope="col">First Name</th>
                            <th scope="col">Last Name</th>
                            <th scope="col">Update</th>
                            <th scope="col">Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        {APIData.map((data) => {
                            return (
                                <tr>
                                    <td>{data.firstName}</td>
                                    <td>{data.lastName}</td>
                                    <td>
                                        <Link href={`/update?id=${data.id}&firstName=${data.firstName}&lastName=${data.lastName}`}>
                                            <button
                                                // onClick={(data) => {
                                                //     <Update data={data}/>
                                                // }}
                                                className='btn btn-secondary'>
                                                Update
                                            </button>
                                        </Link>
                                    </td>
                                    <td>
                                        <button
                                            onClick={() => onDelete(data.id)}
                                            className='btn btn-danger'>
                                            Delete
                                        </button>
                                    </td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
            <Link href="/create">
                <button
                    className='btn btn-light fw-bold'>
                    Add
                </button>
            </Link>
        </>
    )
}

下面是我传递数据的另一个组件。但是它显示为'undefined'

'use client';
import { useState, useEffect } from "react";
import axios from "axios";
import { useRouter } from 'next/navigation';
import Link from "next/link";

export default function Update() {
    const { push, query } = useRouter()
    const { id, firstName, lastName } = query ;
   

    const [firstName2, setFirstName] = useState('');
    const [lastName2, setLastName] = useState('');
    const updateAPIData = (e) => {
        e.preventDefault();
        axios.put(`https://64241e5a47401740433376dd.mockapi.io/crudData/${id}`, {
            firstName2,
            lastName2,
        }).then(() => {
            push('/')
        })
    }

    return (
        <>
            <div>
                <p className="mb-5 text-light text-center pt-5 fs-3 fw-bold">Update item</p>
                <form className="mt-5" >
                    <div className="form-group text-start ">
                        <label className="text-muted mb-3">First Name</label>
                        <input
                            type="text"
                            className="form-control"
                            placeholder="First Name"
                            value={firstName}
                            onChange={(e) => setFirstName(e.target.value)}
                        />
                    </div>
                    <div className="form-group text-start">
                        <label className="text-muted mb-3 mt-3">Last Name</label>
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Last Name"
                            value={lastName}
                            onChange={(e) => setLastName(e.target.value)}
                        />
                    </div>
                    <div className="form-group text-start">
                    </div>

                    <div className='d-flex justify-content-center mt-4'>
                        <Link href="/"><button
                            type="submit"
                            className="btn btn-secondary me-5"
                        >
                            Cancel
                        </button></Link>
                        <button
                            type="submit"
                            className="btn btn-primary"
                            onClick={updateAPIData}
                        >
                            Submit
                        </button>

                    </div>
                </form>
            </div>
        </>
    )
}
gijlo24d

gijlo24d1#

next/router

您的错误'Cannot destructure property 'id' of 'query' as it is undefined.'与props无关,而是与next/router有关。
这是因为router可能在初始渲染之前尚未更新,在这种情况下,像query这样的键将如docs中所述未定义。
如果query未定义,显然不能执行const { id, firstName, lastName } = query;
你可以做的是:

const { id, firstName, lastName } = query || {} ;

在这种情况下,如果query是undefined,那么所有被破坏的prop也将是undefined,而不会抛出错误。

prop

另外,将props传递给Update组件(data={data}),而不接受任何参数:
您需要接受这样的数据,以便在Update组件中访问它:

export default function Update({data})

相关问题