javascript - 错误 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}/>
解决方案
这是因为您的初始状态没有这些属性,要么填充您的初始状态对象:
const initialState = {
"main": {
"first": {},
"second": {}
}
}
const [fetchApiData, setApiData] = useState(initialState);
或使用可选链接
<BigNews
id={props.content.main.first?.id}
title={props.content.main.first?.name}/>
推荐阅读
- twilio - 在对话流中获取用户的位置
- android - 在 React Native 中为 Android 4.X 启用 TLS 1.1/1.2
- tsql - 如何从 cte 更新第二个表以使其可靠工作
- python - RequestsLibrary 支持带有 pabot 的并行执行套件吗?
- r - R在data.table中按组创建递归变量
- javascript - 无法在函数中推送数组
- r - R 绘制生存曲线并计算特定时间的 P 值
- swift - 如何在 SwipeCellKit 中实现左右滑动
- ansible - 使用 ansible 编辑 json 文件
- rabbitmq - 检查rabbitmq服务器是否存活的方法