【问题标题】:TypeError: Cannot read property '0' of undefined with React jsTypeError:无法使用 React js 读取未定义的属性“0”
【发布时间】:2021-08-22 14:36:44
【问题描述】:

所以,我正在构建一个字典库,试图使用 Axios 获取 API 数据,一切正常,但有时它会抛出 "TypeError: Cannot read property '0' of undefined " 对于某些单词。可能是什么问题?因为当我尝试获取某些单词的含义时,它可以正常工作,但对于某些单词,它会引发错误。代码如下

      function App() {    
    const [mapvalue, setMapValue] = useState([])

        const reqLibrary = () => {
            axios.get(dictionaryapi)
            .then((respone) => {
            setMapValue(respone.data.def[0].tr)
            //console.log(respone.data.def[0].tr[0].mean)
        })
      }

      return (
        </div>
      <button onClick={reqLibrary}> Get Words </button>
      <ul>
        {mapvalue.map((response) => (
          <li> {response.mean[0].text} </li>
        ))}
      </ul>
    </div>
     )

}

【问题讨论】:

    标签: reactjs api axios


    【解决方案1】:

    你应该做空检查。这会对你有所帮助。

    setMapValue(respone?.data?.def?.[0]?.tr)
    

    以这种方式进行空值检查称为Optional_chaining

    详细了解Optional_chaining

    【讨论】:

    • 感谢您的回复,但我仍然遇到与以前相同的错误。 API 显示单词的含义并引发某些单词的错误。
    • 在任何地方添加空检查,这里也是response.mean?.[0]?.text
    • 我没明白你的意思是“在任何地方添加空检查,这里也是 response.mean?.[0]?.text”?如果您能帮我解决这个问题,我将不胜感激
    • 是的,只要您认为 value 可以为 null,您就可以使用 ?. 表示法访问
    猜你喜欢
    • 2022-11-17
    • 2020-12-24
    • 2022-01-01
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 2021-07-25
    • 2021-01-06
    • 2017-11-25
    相关资源
    最近更新 更多