【问题标题】:"Objects are not valid as a React child" react error\"Objects are not valid as a React child\" 反应错误
【发布时间】:2023-01-17 01:30:06
【问题描述】:

REACT 未显示数据,并收到以下错误:“对象作为 React 子项无效。如果您打算呈现子项集合,请改用数组”

来自 MongoDB 集合的记录被提取并收集在一个对象数组中。然后我使用 .map() 函数生成要由 Display 组件呈现的元素数组。每个 元素包括接收两个道具(firstName 和 age)的组件 我仍然不明白我的错误在哪里......

感谢帮助!

单记录.js:

    const SingleRecord = (firstName, age) => {    
        return (
        <li className="singe-record">
            {firstName} is {age} years old.
        </li>
        );
    }
    
    export default SingleRecord;

显示.js:

    function Display() {
        const [records, setRecords] = useState();
        const dataArray = [];

        const fetchRecords = () => {
            fetch('http://localhost:3001/users')
            .then(async response => {
                const isJson = await response.headers.get('content-type')?.includes('application/json');           
                const data = isJson ? await response.json() : null;

            for (const elem of data) {
            let elemObj = {
                _id: elem._id, 
                firstName: elem.firstName,
                age: elem.age};
                dataArray.push(elemObj);
            }
                setRecords(dataArray);

                // check for error response
            if (!response.ok) {
                    // get error message from body or default to response status
            const error = (data && data.message) || response.status;
            return Promise.reject(error);
            }
            })
            .catch(error => {
                console.error('There was an error!', error);
            });
        }

        useEffect(() => {  
            fetchRecords();
            // eslint-disable-next-line react-hooks/exhaustive-deps
        }, []);

        if (!records) {
            return null;
        }

        const LI = records.map(elem => {
                    let fn = elem.firstName;
                    let ageee = elem.age;
                    return <li><SingleRecord firstName={fn} age={ageee} /></li>
        })

    return (
        <div className="records-display">
        <h2>Records:</h2>
        <ul className ="records-list">
            {records.map(elem => {
                let fn = elem.firstName;
                let ageee = elem.age;
                return <li><SingleRecord firstName={fn} age={ageee} /></li>
             })}
        </ul>      
        </div>
    );
    }

app.js(后端):

    const { MongoClient } = require("mongodb");
    const uri = "...hidden...";
    const client = new MongoClient(uri);
    const database = client.db('holdocsDB');
    const records = database.collection('records');

    app.get('/users', async (req, res) => {
        const cursor = await records.find();  
        const results = await cursor.toArray();
        res.send(results);         
    })
        
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
        // set locals, only providing error in development
        res.locals.message = err.message;
        res.locals.error = req.app.get('env') === 'development' ? err : {};

        // render the error page
        res.status(err.status || 500);
        res.json('error');
    });


【问题讨论】:

  • SingleRecord = (firstName, age)应该是SingleRecord = ({ firstName, age}),道具不是参数,它们都在一个对象中。尝试渲染 {firstName} 会导致您渲染 props 对象,而 React 清楚地告诉您这是一个问题。而且您没有使用 LI 变量。你读过错误吗?养成总是阅读错误的习惯,不要忽视它们。
  • @AndyRay,答案就在那里。
  • 一行可以回答很多问题,所以我放弃了玩答案游戏,但是这次为什么不呢

标签: javascript node.js reactjs express mern


【解决方案1】:

SingleRecord = (firstName, age)应该是SingleRecord = ({ firstName, age })

道具不作为参数传递,它们都在一个对象中。尝试渲染 {firstName} 会导致您渲染 props 对象,而 React 清楚地告诉您这是一个问题。

而且您没有使用 LI 变量。你读过错误吗?养成总是阅读错误的习惯,不要忽视它们。

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 1970-01-01
    • 2023-01-25
    • 2020-01-12
    • 2020-06-01
    • 1970-01-01
    • 2020-12-09
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多