首页 > 解决方案 > 错误 undefined is not an object React Native

问题描述

我有这种格式的 .JSON:

{
    "main": {
        "first": {
            "id": "123",
            "name": "abc"
        },
        "second": {
            "id": "321",
            "name": "bca"
        }
    }
}

在调用 API 之前,我以这种方式创建状态:

const [fetchApiData, setApiData] = useState({main:{}});

我通过道具将我的 fetchApiData 传递给孩子,例如:

<Index content={fetchApiData}/>

但是,当我在孩子中调用它时,错误说:

undefined 不是对象!

子组件:

<BigNews
id={props.content.main.first.id}
title={props.content.main.first.name}/>

标签: javascriptreactjsreact-nativereact-native-androidreact-state

解决方案


这是因为您的初始状态没有这些属性,要么填充您的初始状态对象:

const initialState = {
  "main": {
      "first": {},
      "second": {}
  }
}

const [fetchApiData, setApiData] = useState(initialState);

或使用可选链接

<BigNews
  id={props.content.main.first?.id}
  title={props.content.main.first?.name}/>

推荐阅读