gpt4 book ai didi

javascript - 如何修复 'Objects are not valid as a React child (found: object with keys )'

转载 作者:行者123 更新时间:2023-11-29 22:56:15 25 4
gpt4 key购买 nike

我想导出这个文件中的一个对象,配置文件:

const CURRENT_YEAR = ( new Date() ).getFullYear()

export default { CURRENT_YEAR }

当我在 footer.js 中导入它时:

import React from 'react'
import CURRENT_YEAR from '../../config'

const footer = () => (
<div >
@NBA { CURRENT_YEAR } All rights reserved.
</div>
)

export default footer

cli 中没有错误,但 React 抛出此错误:

Objects are not valid as a React child (found: object with keys {CURRENT_YEAR}). If you meant to render a collection of children, use an array instead.

最佳答案

删除导出中的括号:

const CURRENT_YEAR = ( new Date() ).getFullYear()

export default CURRENT_YEAR

否则你将 Date 封装到一个对象中,或者你可以这样做:

在 config.js 中:

const CURRENT_YEAR = new Date().getFullYear();

const config = {
CURRENT_YEAR
};

export default config;

在 footer.js 中:

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import config from "../../config";

function App() {
return <div>
@NBA {config.CURRENT_YEAR} All rights reserved.
</div>;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

关于javascript - 如何修复 'Objects are not valid as a React child (found: object with keys )',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56556853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com