我如何访问React道具中的嵌套对象属性
How do I access nested object properties within React props
从这个问题开始- Javascript -我如何访问嵌套在其他对象中的对象的属性
标准点符号似乎不能用于访问React state/props中的嵌套对象属性
这是给道具如下:我如何检索纬度?
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')
);
相关文章:
- 访问键中包含空格的嵌套属性
- 如何将id数组与带下划线的对象数组嵌套属性进行比较
- 正在检查对象javascript中是否存在嵌套属性
- 更新JavaScript对象中的嵌套属性
- 使用 jQuery 传递的 Rails 嵌套属性
- 如何迭代json对象的嵌套属性并创建新的数组列表
- 如何正确传递具有排列属性的嵌套属性?(JSX)
- 如何动态获取对象的嵌套属性
- AngularJS - 包含嵌套属性指令的内容
- 嵌套属性作为函数参数
- 猫鼬:嵌套属性上为空
- 如何检查主干模型中的嵌套属性是否已更改
- 在 ngRepeat 中筛选嵌套属性
- 筛选器深层嵌套属性返回空数组
- 支持流星和铁路由器中具有嵌套属性的多个参数
- 主干虹吸嵌套属性
- 访问 JavaScript 中的嵌套属性
- 在 AJAX 响应中查找嵌套属性,这是 try/catch 的情况
- 从嵌套属性数组中获取对象嵌套值
- JQuery,从嵌套属性中访问对象的根属性