axios React -如何引用reponse.data状态?

yhived7q  于 2023-01-17  发布在  iOS
关注(0)|答案(2)|浏览(126)

React新手,在理解如何从response.data引用对象数据方面有困难。请考虑以下代码:

import React, {useRef, useState, useEffect} from "react";
import UserService from "../services/user.service";
import AuthService from "../services/auth.service";
   
export const getUser = () => {
    
    // Retrieve user info from locally stored JSON
    const currentUser = AuthService.getCurrentUser();
    const [user, setUser] = useState("");

    useEffect(() => {
        getUser();
    }, []);

    const getUser = () => {

        // Retrieve user info from DB using user id
        UserService.getUser(currentUser.id)
            .then(response => {
                setUser(response.data); // This is what I what I want to reference
                console.log(response.data);
            })
            .catch(e => {
                console.log(e);
            });
    };

    return (
        <div>
          {user.username}
        </div>
    );
};

我看到控制台中正确返回了数据:{用户名:'GlennQuagmire'}
使用Webstorm中的调试工具,我看到用户加载了这个值。但是当我们开始呈现{user.username}时,什么也没有显示。我做错了什么?

ws51t4hk

ws51t4hk1#

请看代码,我使用了公共API作为数据库,但您可以将其与您的代码相关联。我认为您需要使用response.json(),然后设置data。同样,当您将用户设置为对象时,初始的useState应声明为空对象const [user, setUser] = useState({});

const {useEffect, useState} = React;

const App = () => {
    //const currentUser = AuthService.getCurrentUser();
    const [user, setUser] = useState("");

    useEffect(() => {
        getUser();
    }, []);

    const getUser = () => {
    // Retrieve user info from DB using user id
    fetch('https://api.agify.io/?name=Glenn Quagmire')
      .then((response) => response.json())
      .then((data) => {
        setUser(data);
        console.log(data)
      }).catch(e => {
        console.log(e);
      });
    };

    return (
        <div>
          {user.name}
        </div>
    );
};
ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
envsm3lx

envsm3lx2#

我找到了答案,在return块中建模:

return (
        <div>
          {user && user.map((user, index) => (  
            <h1>{user.username}</h1>
          ))}
        </div>
    );
};

看起来像是一个迂回的方式来获得一个单一的数据在那里,但它的工作。如果任何人有更好的建议,随时分享。

相关问题