[英]Objects are not valid as a React child -> Build time error -> next js typescript
Return object from function in build time error... when I build my app(npm run build).在构建时错误中从 function 返回 object... 当我构建我的应用程序时(npm 运行构建)。 show me this error
告诉我这个错误
->Objects are not valid as a React child (found: object with keys {name, age}). -> 对象作为 React 子项无效(找到:object,键为 {name, age})。 If you meant to render a collection of children, use an array instead.
如果您打算渲染子集合,请改用数组。
That is my code那是我的代码
const obj = {
name:"A",
age:20
}
function ObjFileReturn():[obj:{name:string,age:number}] {
return [obj];
}
export default ObjFileReturn;
The question is -> How can I return obj from a function using ts问题是 -> 如何使用 ts 从 function 返回 obj
please help me and ignore my writing style.请帮助我并忽略我的写作风格。
If you are trying to return the object as a component you need to first stringify the object or transform it from an object type.如果您尝试将 object 作为组件返回,您需要首先将 object 字符串化或将其从 object 类型转换。 Objects are not valid JSX/React elements.
对象不是有效的 JSX/React 元素。
You can do:你可以做:
type objType = {
name: string
age: number
}
const obj: objType = {
name: "A",
age: 20
}
function ObjFileReturn() {
return <div>{JSON.stringify(obj, null, '\t'}</div>
export default ObjFileReturn;
JSON.stringify() converts the object to string which you can use inside a div to return from the functional comonent. JSON.stringify() 将 object 转换为字符串,您可以在 div 中使用该字符串从函数组件返回。 The extra parameters in strigify pretty-print it so that it remains formatted.
strigify 中的额外参数漂亮地打印它,以便它保持格式化。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Hope that helps!希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.