错误未定义不是 object React Native

Error 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 传递给 children,例如:

<Index content={fetchApiData}/>

但是,当我在 child 中调用它时,错误提示:

undefined is not an object!

Child 分量:

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

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

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

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

或使用Optional chaining

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