gpt4 book ai didi

javascript - 如何访问 React props 中的嵌套对象属性

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:29 24 4
gpt4 key购买 nike

接着这个问题 - Javascript - How do I access properties of objects nested within other Objects

标准点表示法似乎不适用于访问 React state/props 中的嵌套对象属性

下面给出了 Prop :如何检索纬度?

Object {
id: "138451",
name: "Attendant",
key: "Taiwan",
defaultAnimation: 2,
position: Object
{
latitude:0.5,
longitude: -0.14
}
componentWillReceiveProps(nextProps){
console.log("its getting props");
console.log(nextProps.markers[0]) // this works
//displays Object {position: Object, key: 2, defaultAnimation: 2}
console.log(nextProps.markers[0].position) //so does this
//displays Object {latitude: 51.5193, longitude: -0.140725}
console.log(nextProps.markers[0].position.longitude) //breaks with the error message

TypeError: Cannot read property 'longitude' of undefined
at GooleMapComponent.componentWillReceiveProps (http://localhost:3000/app/app.js?....

最佳答案

这里演示了如何使用点表示法在 Child 的 componentWillReceiveProps 方法以及 render() 方法中访问 React props 中的嵌套对象属性: http://codepen.io/PiotrBerebecki/pen/qaKyYj

class App extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
this.state = {
markers: null
}
}

handleClick() {
this.setState({
markers: [
{
id: "138451",
name: "Attendant",
key: "Taiwan",
defaultAnimation: 2,
position: {
latitude: 0.5,
longitude: (-Math.random()).toFixed(2)
}
}
]
});
}

render() {
return (
<div>
<h1>App</h1>
<button onClick={this.handleClick}>Send State via Props</button>
<Child markers={this.state.markers}/>
</div>
);
}
}

class Child extends React.Component {
componentWillReceiveProps(nextProps) {
console.clear();
console.log('in componentWillReceiveProps', nextProps.markers[0]);
console.log('in componentWillReceiveProps', nextProps.markers[0].position);
console.log('in componentWillReceiveProps', nextProps.markers[0].position.longitude);
}

render() {
if (this.props.markers) {
return (
<div>
<h5>Child happy :) child received an array via props</h5>
Longitute: {this.props.markers[0].position.longitude}
</div>
);
} else {
return (
<div>
<h5>Child not happy :( Child received 'null' via props</h5>
</div>
);
}
}
}

ReactDOM.render(
<App />,
document.getElementById('app')
);

关于javascript - 如何访问 React props 中的嵌套对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40017854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com