【问题标题】:Called api not read object调用 api 未读取对象
【发布时间】:2021-01-22 10:56:20
【问题描述】:

当我使用 console.log 调用详细信息时,没有任何显示错误 exam: console.log(coin.description.en); 但是当我编写此代码时 {coin.description.en} 在渲染中不起作用并显示此错误: TypeError:无法访问属性“en”,coin.description 未定义

import React, {useEffect, useState} from "react";
import {connect} from 'react-redux';
import axios from 'axios';

function CoinDetail({...props}) {
    const [coin,setCoin] = useState([]);

    useEffect(() => {
        getCoinDetail(API_URL+'ripple');
    },[]);

    const getCoinDetail = (id) => {
        axios.get(id).then(res => {
            setCoin(res.data);
            console.log(res.data);
        });
    }
    
    return (
        <>
            Id: {coin.id}<br/>
            Name: {coin.name}<br/>
            Symbol: {coin.symbol}<br/>
            Description: {coin.description.en}<br/>
        </>
    );
}

function mapStateToProps(state,ownProps) {
    const coinId = ownProps.match.params.coinId;
    return {
        coinId
    }
}

export default connect(mapStateToProps)(CoinDetail);

【问题讨论】:

    标签: reactjs api react-redux


    【解决方案1】:

    尝试用{coin.description &amp;&amp; coin.description.en} 代替{coin.description.en}

    【讨论】:

    • 非常感谢,但为什么要使用两次 coin.description 呢?
    • coin.description.en 仅在coin.description 未定义或为空时返回。因此,我们为此使用&amp;&amp;
    • 我想从 url 中获取 coinId,我测试了但是当我写 alert work 正确给出 id 时没有工作,但是当我使用 url+coinId 时不起作用,为什么?常量 coinTest = props.coinId;警报(coinTest);
    • @NikolayAndrv 你能在codesandbox中分享你的代码吗
    猜你喜欢
    • 2016-11-23
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多