简体   繁体   English

“对象作为 React 子项无效”反应错误

[英]"Objects are not valid as a React child" react error

the data is not displayed by REACT and the following error is received: "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead" REACT 未显示数据,并收到以下错误:“对象作为 React 子项无效。如果您打算呈现子项集合,请改用数组”

The records from MongoDB collection are fetched and gathered in an array of objects.来自 MongoDB 集合的记录被提取并收集在一个对象数组中。 then I use the.map() function to produce the array of elements to be rendered by the Display component.然后我使用 the.map() function 生成要由 Display 组件呈现的元素数组。 Each element includes the component which receives two props (firstName and age) i still do not see where is my mistake...每个元素都包含接收两个道具(firstName 和 age)的组件,我仍然看不出我的错误在哪里......

thanx for help!谢谢你的帮助!

SingleRecord.js:单记录.js:

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

Display.js:显示.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 (backend): 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) should be SingleRecord = ({ firstName, age }) SingleRecord = (firstName, age)应该是SingleRecord = ({ firstName, age })

Props aren't passed as individual arguments, they're all in the first argument as an object. Trying to render {firstName} is causing you to try to render the entire props object, and the react error React is telling you that's an issue.道具不是作为单独的 arguments 传递的,它们都在第一个参数中作为 object。尝试渲染{firstName}导致您尝试渲染整个props object,反应错误 React 告诉你这是一个问题.

And you aren't using the LI variable.而且您没有使用 LI 变量。 And did you read the error?你读过错误吗? Get in the habit of always reading errors, don't ignore them.养成总是阅读错误的习惯,不要忽视它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM