TypeError: Cannot read property 'quote' of undefined React js

TypeError: Cannot read property 'quote' of undefined React js

总而言之,我正在使用 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>

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

以下是我建议如何调试以了解您的问题:

  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>