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
193 views
in Technique[技术] by (71.8m points)

reactjs - React Hook Initializing the state with server call

Working with a react component using hooks. I am attempting to assign values to my state after an Axios call. The data is correctly returned and it appears the state is correctly updated; however, the DOM is not updating with the values. Is this the proper method for doing this?

export const Main = (props) => {
    const { token } = useParams()    
    const [user,setUser] = useState({name:""})        
    useEffect(()=>{
        const getUser = async() =>{
            const response = await API.post("usrinfo",{token:token})
            setUser({name:response.data.name});
        }
        getUser()
    },[token])
    return(
        <div className="main-header">{user.name}</div>
    );
}
question from:https://stackoverflow.com/questions/65643937/react-hook-initializing-the-state-with-server-call

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

1 Answer

0 votes
by (71.8m points)

Found the issue:

AXIOS returns a data portion in it's response so instead of response.data.name it should be response.data.data.name.

Thanks for all your responses.


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

...