我正在使用 ContactCard 中的状态将我的道具发送到 ContactDetails 页面。但是当使用 useLocation 挂钩时,我在 Location.state 中收到 null。
ContactCard.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const ContactCard = (props) => {
const { id, name, email } = props.contact;
const removeId = (id) => {
props.getDeleteId(id);
}
return (
<>
<div>
<Link to={{ pathname: `/ContactDetails/${id}` }} state= {props.contact} style={{ cursor: "pointer" }}>
<i className="bi bi-person-circle"></i>
<label className='p-1'>{name}</label>
<label>{email}</label>
</Link>
<i className="bi bi-trash ml-10" onClick={() => removeId(id)} style={{ cursor: "pointer", color: "red", marginLeft: "48px" }}></i>
</div>
<div className='ul'></div>
</>
);
}
export default ContactCard;
联系方式.jsx
import React from 'react';
import { useLocation } from 'react-router-dom';
const ContactDetails = () => {
const location = useLocation();
const { contact } = location.state || {};
if (!contact) {
return <div>No contact data available.</div>;
}
console.log(contact);
return (
<>
<div>
<div>{contact.name}</div>
<div>{contact.email}</div>
</div>
<div className='ul'></div>
</>
);
};
export default ContactDetails;
props.contact 中的数据- {id: 'ec49b94a-eebf-4111-8e7e-40ea1a72a92e', name: 'abc', email: '[email protected]'}
我应该能够在 location.state 中接收 props.contact 数据
代码将
props.contact
作为传递给路由状态,即 state={props.contact}
,但 props.contact
上没有任何 contact
属性。
const { id, name, email } = props.contact;
直接从
id
访问 name
、email
和 location.state
:
const location = useLocation();
const { id, name, email } = location.state || {};
或将联系方式传递至
state.contact
:
<Link
to={`/ContactDetails/${id}`}
state={{ contact: props.contact }} // location.state.contact 🙂
style={{ cursor: "pointer" }}
>
<i className="bi bi-person-circle"></i>
<label className='p-1'>{name}</label>
<label>{email}</label>
</Link>