【问题标题】:TypeError: Cannot read property 'quote' of undefined React jsTypeError:无法读取未定义的 React js 的属性“引用”
【发布时间】:2021-10-13 12:26:38
【问题描述】:

总结一下,我正在使用 React js 创建一个报价生成器。使用 React axios 从模拟 API 获取数据。

但是,当我尝试显示报价时,它给了我上述错误

我得到错误的行:{quotes[quoteIndex].quote}

(quotes) 被数据填充 (quoteIndex) 基本上是数组中的索引 (.quote) 是数据中的属性

请查找相关代码

// sample from .json file data
"quotes": [
    {
    "id":0,
    "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "id":1,
    "quote": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  }
 ]
}


const [quotes, setQuotes] = useState([]);
const [quoteIndex, setQuoteIndex] = useState(0);

// fetching the data
const getData = async() =>{
        try{
            const response = await Axios.get("/quotes");

            if(response && response.data){
                setQuotes(response.data);
                console.log(response.data);
            }

        }catch(error){
            console.log(error);
        }
        
    }


//this inside the return statement
<div className="styleQuote">
                    <h3 className="styleText" >{quotes[quoteIndex].quote}</h3>
                </div>

【问题讨论】:

    标签: javascript reactjs axios fetch undefined


    【解决方案1】:

    这是处理异步加载的数据时非常常见的问题。

    以下是我建议调试它以了解您的问题的方法:

    1. 删除有问题的代码,以便您可以观察正在发生的事情。

    2. 在您的组件中添加console.log(quotes)。你会看到它记录了[],然后又记录了你的数组。

    3. 接下来添加console.log(quotes[quoteIndex])。请注意,它记录了undefined,然后是一个对象。

    考虑到虽然值为undefined,但您不能将其视为对象并尝试访问其属性。

    1. 在使用之前添加一个检查以确保该值是一个对象:
    // Nullsafe operator
    quotes[quoteIndex]?.quote
    // Or ternary
    quotes[quoteIndex] ? quotes[quoteIndex].quote : null
    

    这是一个模拟示例:

    const async_quotes = [
      {
        "id":0,
        "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
        "author": "Thomas Edison"
      },
      {
        "id":1,
        "quote": "You can observe a lot just by watching.",
        "author": "Yogi Berra"
      }
     ]
    
    const {useState, useEffect} = React;
    
    const index = 1;
    
    const Example = () => {
      const [quotes, setQuotes] = useState([]);
      
       useEffect(() => {
         setTimeout(() => {
           setQuotes(async_quotes);
         }, 3000);
       }, []);
       
       console.log("quotes:", quotes);
       console.log("single quote:", quotes[index]);
       
       return <div>{quotes[index] ? quotes[index].quote : ''}</div>
    }
    
    ReactDOM.render(<Example />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

    • 报价[quoteIndex] ? quote[quoteIndex].quote : null 这个检查对我有用,但只是为了确认这个检查的条件是什么 (quotes[quoteIndex]),我知道如果这是真的,这个 (quotes[quoteIndex].quote) 将显示 else null
    • 它正在进行truthy 检查。在这种情况下,它只是验证它不是undefined(这是假的)
    • 对不起,我又问这个问题了。

      { quotes[quoteIndex].quote}

      //这给了我上面的错误。但是,使用三元检查,运行良好

      {quotes[quoteIndex] ? quote[quoteIndex].quote : null}

      这是否意味着它之前也没有未定义?
    猜你喜欢
    • 2022-11-17
    • 2020-12-24
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2021-07-25
    • 2021-01-06
    • 2017-11-25
    • 2023-03-19
    相关资源
    最近更新 更多