2017-06-13 8 views
-2

は、私は次のようなメッセージを持っている(APIフェッチして)未定義のプロパティ「SETSTATE」を読み取ることができません
これは次のコード行にある:ここ
this.setState({users: data.users});は、私は私の「ユーザー」状態の変数を設定しようとしているとき


である

`インポートが反応私のクラス、 '反応' から{コンポーネント}。

クラスのユーザーコンポーネント{

constructor(props) { 
    super(props); 
    this.state = { 
     users: [] 
    }; 
} 

componentWillMount() { 
    this.getUsers(); 
} 

getUsers =() => { 
    let myHeaders = new Headers({ 
     'Authorization': 'Basic '+btoa('[email protected]:password'), 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }); 

    fetch('https://dev-api/v1/user/', { 
     method: 'GET', 
     headers: myHeaders 
    }).then(function(response) { 
     if (!response.ok) { 
      throw Error(response.statusText); 
     } 
     return response; 
    }).then(function(response) { 
     response.json().then(function(data) { 
      this.setState({users: data.users}); 
     }); 
    }).catch(function(error) { 
     console.log(error); 
    }); 
} 

render() { 
    return (
     <table className="striped bordered"> 
      <thead> 
       <tr> 
        <th>email</th> 
        <th>Firstname</th> 
        <th>Lastname</th> 
       </tr> 
      </thead> 
      <tbody> 
      {this.state && this.state.users && this.state.users.map(user => 
       <tr> 
        <td>{user.username}</td> 
        <td>{user.firstname}</td> 
        <td>{user.lastname}</td> 
       </tr> 
      )} 
      </tbody> 
     </table> 
    ); 
} 

}

輸出のデフォルトのユーザーを拡張; `

どうもありがとう! 。。 `})を((応答)=> { response.json()を((データ)=> { this.setState({ユーザー:データ

+3

結合の問題は、矢印の関数を使用します。 –

+0

ありがとうございました! – banibanc

答えて

0
constructor(props) { 
    super(props); 
    this.state = { 
     users: [] 
    }; 
    this.getUsers = this.getUsers.bind(this); //************ add this 
} 

getUsers =() => { 
    let self = this //************ add this 
    let myHeaders = new Headers({ 
     'Authorization': 'Basic '+btoa('[email protected]:password'), 
     'Accept': 'application/json', 
     'Content-Type': 'application/json' 
    }); 

    fetch('https://dev-api/v1/user/', { 
     method: 'GET', 
     headers: myHeaders 
    }).then(function(response) { 
     if (!response.ok) { 
      throw Error(response.statusText); 
     } 
     return response; 
    }).then(function(response) { 
     response.json().then(function(data) { 
      self.setState({users: data.users}); //****** replace this 
     }); 
    }).catch(function(error) { 
     console.log(error); 
    }); 
} 
+0

いいえ、すでに試してみましたが、動作していません: -/ – banibanc

+0

getUserMethodでこれを 'let self = this 'のようなローカル変数に設定し、代わりにself.setState this.setState –

+0

@banibanc上記のコードを今すぐ試... –

関連する問題