[英]Accessing nested JSON data with React Hooks & Props
I'm trying to access data further down into my JSON file.我正在尝试进一步访问我的 JSON 文件中的数据。 I am able to easily access data in the first two data sets in rows
and area
:我能够轻松访问rows
和area
中前两个数据集中的数据:
"rows": [
{
"uid":"001",
"type": "Lorem ipsum",
"area": [
{
"name": "London",
"number": "12345",
"wait": {
"start": {
"start_time": 1585129140,
"delay": 300
},
"end": {
"end_time": 1585130100,
"delay": 300
}
},
"in": 1585129140,
"out": 1585130100,
},
However when I try to access the data under wait which includes this block:但是,当我尝试访问包含此块的正在等待的数据时:
"wait": {
"start": {
"start_time": 1585129140,
"delay": 300
},
"end": {
"end_time": 1585130100,
"delay": 300
}
},
No data is getting returned on screen from my jsx file, but it is available in the console log屏幕上没有从我的 jsx 文件返回任何数据,但它在控制台日志中可用
const TimeTracker = (props) => {
const trainTime = useState(props.data);
console.log(props.data);
return (
<>
<div className={style.timeLabel}>
<div className={style.startTime}>{trainTime.start_time}</div>
<div className={style.endTime}></div>
</div>
</>
)
};
export default TimeTracker;
wait:
start:
start_time: 1585129140
delay: 300
__proto__: Object
end:
end_time: 1585130100
delay: 300
__proto__: Object
__proto__: Object
I've used the same pattern for passing props in other components and it works fine on the first two levels so I don't understand why it's not working.我在其他组件中使用了相同的模式来传递道具,并且它在前两个级别上工作正常,所以我不明白为什么它不起作用。 How do I get data from further in this JSON?我如何从这个 JSON 中进一步获取数据?
useState
returns a tuple with the object and a function to set the value on the object. You probably need to change your component to something like this: useState
返回一个包含 object 和 function 的元组以设置 object 上的值。您可能需要将组件更改为如下所示:
const TimeTracker = (props) => {
const [trainTime, setTrainTime] = useState(props.data);
console.log(props.data);
return (
<>
<div className={style.timeLabel}>
<div className={style.startTime}>{trainTime.start_time}</div>
<div className={style.endTime}></div>
</div>
</>
)
};
export default TimeTracker;
A nested property can not be accessed by one level of ab
so instead of嵌套的属性不能被一层ab
访问,所以不用
<div className={style.startTime}>{trainTime.start_time}</div>
it should be它应该是
<div className={style.startTime}>{trainTime.wait.start.start_time}</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.