Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

reactjs - React Hooks Getting data from inside an object state

I'm using react hooks to access a state information. In my code, I pass state from one page to another and is successfully able to access it. This is my working code, so far:

    import React, { useEffect, useState } from 'react';

    import { showById, changeStatus } from '../../services/teachers';

    import './styles.css';

    function TeacherPage(props) {
        const [data, setData] = useState(props.location.state);
        const [teacherInfo, setTeacherInfo] = useState(data);
        const [nameInfo, setNameInfo] = useState();

        function handleTeacherInfo(id){
            id = data.teacher._id;
            const response = api.get(`/teacher/${id}`);
            setTeacherInfo(response);
            console.log(teacherInfo);
            setNameInfo(teacherInfo.name)
            console.log(nameInfo);
        }

        useEffect(() =>{
            handleTeacherInfo();
        }, [data])

        return (
        <div className="teacherPage">
            <div className="contentTeacherPage">
                <h1>Professor(a) {data.teacher.name}</h1>
                <div clasname="teacherInfoCard" key={data.teacher._id}>
                    <span>{data.teacher.name}</span>
                    <br></br>
                    <span>{data.teacher._id}</span>
                    <br></br>
                    <span>{data.teacher.email}</span>
                    <br></br>
                    <span>{data.teacher.education}</span>
                    <br></br>
                    <span>Status: {data.teacher.approved}</span>
                    <br></br>
                    <span>{data.teacher.cpf}</span>
                    <br></br>
                    <span>{data.teacher.info}</span>
                    <br></br>
                    <span>{data.teacher.rating}</span>
                    <br></br>
                    <span>{data.teacher.subjects[0]} e {data.teacher.subjects[1]}</span>
                    <br></br>
                    <span>{data.teacher.education[0]}</span>
                    <br></br>
                    {/* {data.teacher && data.teacher.teacher.map((teacher) => {
                        return (
                            <span>alalal</span>
                        )
                    })} */}
                    <button onClick={approveTeacher}>Aprovar</button>
                </div>
            </div>
        </div>
    )
}

export default TeacherPage;

I am able to access data with this lengthy-expression, {data.teacher.<field>}, but I was looking to pass them all to a state so I would be able to map it, because some of these fields are arrays.

In the function below, I am setting the teacherInfo state as the response from the api.get and able to see all of its data, but am unable to see specific data from the state.

console.log(teacherInfo) returns the data, but console.log(teacherInfo.name) returns undefined (name is an existing field).

       function handleTeacherInfo(id){
            id = data.teacher._id;
            const response = showById(id);
            setTeacherInfo(response);
            console.log(teacherInfo);
            setNameInfo(teacherInfo.name)
            console.log(nameInfo);
        }

How can I get specific data from the state? I believe either I'm missing something or I'm declaring something wrong, but I don't know what.

For better visualization, console.log(teacherInfo) return is this:

teacher:
    approved: false
    availableDays: "asasas"
    classPrice: "R$ 500,00"
    degree: "ddsdsds"
    email: "[email protected]"
    info: "asasas"
    name: "Pedro"
    rating: 10
    registerDate: "2021-01-21T17:19:07.565Z"
    subjects: ["6001e73106a211004877f6e2"]
    __t: "Teacher"
    __v: 0
    _id: "6009b78b3c4c35001d19a346"

Console.log(teacherInfo.name) returns undefined, but should return Pedro


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

setState is asynchronous, so you cannot guarantee that teacherInfo will have been updated when you attempt to call setNameInfo().

You should use the useEffect() hook for that, and pass in teacherInfo as a dependancy using the second parameter:

useEffect(() => { 
    setNameInfo(teacherInfo?.name);
}, [ teacherInfo ]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...