[英]I am trying to send data from one page to another in nextjs but failing
Its giving this error "Error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead."它给出了这个错误“错误:对象作为 React 子项无效(找到:object,键为 {})。如果您打算呈现子项集合,请改用数组。” Please help.
请帮忙。
export default function PostScreen() {
const data = 'Hello';
return (
<>
<div>
<span>Create Post</span>
<Link
href={{
pathname: '/details',
query: data,
}}
>
<a>Click me</a>
</Link>
</div>
</>
);
}
// Another page
function Details(){
const router = useRouter();
const data = router.query;
return (
<div>
<div>
<div>
<strong>Username:</strong> {data}
</div>
</div>
</div>
);
}
query
in href
accepts an object with key value pairs. href
中的query
接受带有键值对的 object。 If you pass string
, it will convert the variable's value of the string to key
and its value will be empty;如果传递
string
,它会将字符串的变量值转换为key
,其值为空;
If you do a console.log(data)
on the /details
page, you get the following:如果你在
/details
页面上执行console.log(data)
,你会得到以下信息:
{ Hello: '' }
React
doesn't support rendering JS objects in the JSX. React
不支持在 JSX 中渲染 JS 对象。 Hence, you see that error.因此,您会看到该错误。
So, to solve your problem, you can give some key to the data and use that key in /details
page to get your data.因此,要解决您的问题,您可以为数据提供一些密钥,并在
/details
页面中使用该密钥来获取您的数据。
For example:例如:
export default function PostScreen() {
const data = 'Hello';
return (
<div>
<span>Create Post</span>
<Link
href={{
pathname: '/details',
query: { message: data },
}}
>
<a>Click me</a>
</Link>
</div>
);
}
// "/details" page
function Details(){
const router = useRouter();
const data = (router.query ?? {}).message;
return (
<div>
<div>
<div>
<strong>Username:</strong> {data}
</div>
</div>
</div>
);
}
Route.query is a object. you should unpack it first, like: Route.query 是一个 object。你应该先解压它,比如:
const {id} = data
Then pass id to the HTML然后将id传给HTML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.