簡體   English   中英

在 React/JSX 中顯示嵌套的 JSON

[英]Displaying Nested JSON in React/JSX

我有一些 JSON 的格式如下:

{
    card_id: "afe1500653ec682b3ce7e0b9f39bed89",
    name: "A.J. Burnett",
    playerattribute: {
        team: "Marlins",
        rarity: "Diamond",
    }
}

我正在嘗試在組件中顯示名稱和團隊。 這就是我所擁有的。

const PlayerProfile = ({ match, location }) => { 
    const { params: { cardId } } = match;
    const [player, setPlayer] = useState(0);
 
    useEffect(() => {
        const fetchData = async () => {
          const result = await axios(
            `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
          ).then((result) => {
            setPlayer(result.data);
          });
        };
        fetchData();
      }, []);

    return (
        <Container component="main">
            Name: {player.name}
            Team: {player.playerattribute.team}
        </Container>
    )
}

export default PlayerProfile;

但是,我收到此錯誤: TypeError: Cannot read property 'team' of undefined

這個名字很好用。 所以我假設這是嵌套 JSON 的問題。

如果預計值為 object,您可能不應該將播放器 state 實例化為 0。

出現錯誤是因為您嘗試訪問在創建時不存在的 object 屬性的屬性。

基本上,您的代碼會嘗試這樣做: {0.playerattribute.team}

0.playerattribute => undefined

解決方法是使用符合 JSX 需求的 state 的條件渲染或默認初始值。

const PlayerProfile = ({ match, location }) => { 
const { params: { cardId } } = match;
const [player, setPlayer] = useState({
    name: "",
    playerattribute: {
        team: ""
    }
});

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
      ).then((result) => {
        setPlayer(result.data);
      });
    };
    fetchData();
  }, []);

return (
    <Container component="main">
        Name: {player.name}
        Team: {player.playerattribute.team}
    </Container>
)
}

export default PlayerProfile;

或者

const PlayerProfile = ({ match, location }) => { 
const { params: { cardId } } = match;
const [player, setPlayer] = useState(null);

useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
        `http://127.0.0.1:8000/api/player-profiles/${cardId}/?format=json`,
      ).then((result) => {
        setPlayer(result.data);
      });
    };
    fetchData();
  }, []);

return (
    <Container component="main">
        Name: {player?.name}
        Team: {player?.playerattribute?.team}
    </Container>
)
}

export default PlayerProfile;

設置 useState const [player, setPlayer] = useState("");

const [player, setPlayer] = useState({
Name: '',
Team: ''
}}

//on your setPlayer you may 
const playerData = result.data;
setPlayer({
Name: playerData.name
Team: playerData.playerattribute.team})

如果您仍然遇到同樣的錯誤,請提供console.log(result)的屏幕截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM