2017-09-28 21 views
0

子コンポーネントがあります。オブジェクトを経由してオブジェクトを渡し、そのオブジェクト内の配列内にインデックス値を見つける必要があります。下のコードを見ると、それはかなり簡単です。私は「My_Items」配列の異なった方法の束を初期化しようとしましたが、私はまだエラーを取得迷惑な反応のエラー... "TypeError:ヌルのプロパティ 'My_Items'を読み取ることができません"

TypeError: Cannot read property 'My_Items' of null 

は、私はこのエラーを取得します。

この配列の値にIndexComponentからアクセスしてこのエラーを回避するにはどうすればよいですか?

import React, {Component} from 'react'; 
import {connect} from "react-redux"; 

function IndexComponent(props) { 
    const { 
    typeName, 
    myObject 
    } = props; 


    const getAtIndex = (type) => { //this function retrieves the index of the desired item inside the My_Items array, inside the larger object 
    let index; 
     myObject.My_Items.map(item => { 
     if(item.title === type) { 
     index = myObject.My_Items.indexOf(item); 
     } 
    }) 
    return index; 
    } 

    return (
     <div> 
     My Desired Index Value: {getAtIndex(typeName)} <br/> 
     </div> 
    ) 
} 

class MyComponent extends Component { 

    render() { 

    const { 
     typeName, 
     myObject 
    } = this.props; 


    return (
      <div className="row"> 
      <div className="col-xl-5"> 

       <IndexComponent typeName={typeName} myObject={myObject} /> 

      </div> 
      </div> 
)} 

export default connect(
    (store) => { 
    return { 
     typeName: store.data.typeName, 
     myObject: store.data.myObject 
    }; 
    } 
)(MyComponent); 
+1

エラーが 'myObject'ことを語っている保護)

data: { myObject: { My_Items: [], // ... }, // ... } 

2のようなものがあるはずです'My_Items'ではなくnullです。 – stybl

+1

'store.data.myObject'は' store.myObject'ではないはずですか? Reduxストアを見せていただけますか? – lilezek

+0

@stybl ok事はそれがnullではない、私はconsole.logオブジェクトと印刷することができますちょうど良い..どのように私はそれがデータを参照してくださいか? – fromspace

答えて

1

store.data.myObjectが初期化される前に、開始をレンダリングMyComponent(およびIndexComponent)のように見えます。私はお勧めします

1)最初の還元状態をチェックしてください。 IndexComponent

return myObject && myObject.My_Items && myObject.My_Items.length ? (
    <div> 
    My Desired Index Value: {getAtIndex(typeName)} <br/> 
    </div> 
) : (null) 

またはpと同様な方法でレンダリングする。(1)

return myObject.My_Items.length ? (
    <div> 
    My Desired Index Value: {getAtIndex(typeName)} <br/> 
    </div> 
) : (null) 
関連する問題