2016-10-13 18 views
0

を反応させるの中にどのように私は、ネストされたオブジェクトのプロパティにアクセスします - Javascript - How do I access properties of objects nested within other Objectsこの質問に続き小道具

標準ドット表記が与えられているリアクト状態/小道具

内のネストされたオブジェクトのプロパティにアクセスするために動作するようには思えません小道具:どのように緯度を取得するのですか?ここで

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?.... 
+1

メッセージ? –

+0

「ブレーク」を定義します。 – deceze

+0

申し訳ありませんが、より明確になっているはずです。私は位置が未定義であることを私に伝えるいくつかのTracker関数エラーを再計算することを見ます。しかし、前の行で私はconsole.logの位置にすることができます。問題のエラーメッセージを参照してください。 – ElJefeJames

答えて

0

は、あなたが子供のcomponentWillReceiveProps方法ならびにrender()方法で両方の小道具を反応させるの内、ネストされたオブジェクトのプロパティにアクセスするには、ドット表記を使用する方法のデモです: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') 
); 
+0

ElJefeJames、ちょうど私の答えを更新しました。これはあなたの後のことですか? –

+1

Piotrありがとう、これは素晴らしい解決策です。問題を解決するために私のモンゴーロードを修正することと組み合わせてこれを使用しました。 – ElJefeJames