从 API 调用中渲染嵌套对象属性

Rendering nested object properties from API call in react

我正在尝试从 API 调用中呈现文本,可直接从 axios.data 对象访问的文本或数字可以正常呈现,但是在 axios.data 内部时有另一个具有自己属性的对象我无法渲染,因为显示错误,错误是“未定义不是对象(评估 'coin.description.en')”,那边的描述是一个对象;我的代码是

function SINGLE_COIN(props) {

    const { id } = useParams()
    console.log(id);
    

    const SINGLE_API = `https://api.coingecko.com/api/v3/coins/${id}?tickers=true&market_data=true&community_data=true&developer_data=true&sparkline=true`

    const [coin, setCoin] = useState({})


     useEffect(() => {
        axios
    .get(SINGLE_API)
    .then(res => {
        setCoin(res.data)
        console.log(res.data)
    })
    .catch(error => {
        console.log(error)
    })
    }, [])


    return (


        <div>
           <h2>{coin.name}</h2>
           <div>{coin.coingecko_score}</div>
           <div>{coin.liquidity_score}</div>
           <div>{coin.description.en}</div>


            <SINGLE_COIN_DATA coin={coin} />
        </div>

    )
}

谢谢!

对于初始渲染(尚未获取数据),它将是空的。所以嵌套 属性 将是未定义的。

请注意更改:

示例 1:

const [coin, setCoin] = useState(null);

..

return (
    <div>
      {coin ? (
        <>
          <h2>{coin.name}</h2>
          <div>{coin.coingecko_score}</div>
          <div>{coin.liquidity_score}</div>
          <div>{coin.description.en}</div>
        </>
      ) : null}
    </div>
  );

示例:2:在访问嵌套时使用可选链接 属性

 return (
    <div>
      <h2>{coin?.name}</h2>
      <div>{coin?.coingecko_score}</div>
      <div>{coin?.liquidity_score}</div>
      <div>{coin?.description?.en}</div>
    </div>
  );

完整代码:working example

export default function SINGLE_COIN() {
  const { id } = useParams()

  const SINGLE_API = `https://api.coingecko.com/api/v3/coins/${id}?tickers=true&market_data=true&community_data=true&developer_data=true&sparkline=true`;

  const [coin, setCoin] = useState(null);

  useEffect(() => {
    axios
      .get(SINGLE_API)
      .then((res) => {
        setCoin(res.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }, []);

  return (
    <div>
      {coin ? (
        <>
          <h2>{coin.name}</h2>
          <div>{coin.coingecko_score}</div>
          <div>{coin.liquidity_score}</div>
          <div>{coin.description.en}</div>
        </>
      ) : null}
    </div>
  );
}