2017-11-22 28 views
1

いくつかのムービーを返すJsonファイルに対してAjaxリクエストを作成しています。Reactネイティブ状態が変更されていません

state = { movies: [] }; 
 

 
    componentWillMount() 
 
    { 
 
     this.getMovies(); 
 
    } 
 

 
    /* 
 
     Make an ajax call and put the results in the movies array 
 
    */ 
 
    getMovies() 
 
    { 
 
     axios.get('https://pastebin.com/raw/FF6Vec6B') 
 
      .then(response => this.setState({ movies: response.data })); 
 
    } 
 

 

 

 
    /* 
 
     Render every movie as a button 
 
    */ 
 
    renderMovies() 
 
    { 
 
     const { navigate } = this.props.navigation; 
 

 
     return this.state.movies.map(movie => 
 
      <ListItem key={ movie.title } 
 
       title={ movie.title } 
 
       icon={{ name: 'home' }} 
 
       onPress={() => 
 
        navigate('Details', { title: movie.title, release: movie.releaseYear }) 
 
       } 
 
      /> 
 
     ); 
 
    } 
 

 
    render() { 
 
     return(
 
      <List> 
 
       { this.renderMovies() } 
 
      </List> 
 
     ); 
 
    }

私が手にエラーは次のとおりです:this.state.mapは関数ではありません。これは映画がまだ空だからです。

私がconsole.log response.dataを実行すると、JSONファイルからすべての行が返されます。問題はこの行の可能性が最も高いです:

.then(response => this.setState({ movies: response.data })); 

誰かが間違っていることを知っていますか?

+0

チェックこのhttps://stackoverflow.com/questions/47027035/why-is-my-react-component-this-state-updateclothing-saying-undefined-even-thou/47028520#47028520 –

+0

結合問題で'getMovies'関数 –

+0

@Raidersあなたのjsonレスポンスの形式が間違っています。チェックアウトしてください。 – jason

答えて

0

getMovies()からtypeof response.dataをログに記録して配列であることを確認してください。

ところで、あなたはrender()であなたのコンポーネントをバインドする必要があります:あなたの問題を解決することがあり

render() { 
    return(
     <List> 
      { this.renderMovies.bind(this)() } 
     </List> 
    ); 
} 

とにかく、selfthen(response => ...)と書いてあり、then(function(response){ ... })ではないので、他の回答に示唆されているように使用する理由はありません。

-1

更新あなたは、AJAXリクエスト以下のように:あなたは間違った場所に初期状態を置く

constructor(props){ 
    super(props); 
    this.getMovies = this.getMovies.bind(this); 
} 
0

/* 
    Make an ajax call and put the results in the movies array 
*/ 
getMovies() 
{ 
    let self = this; 
    axios.get('https://pastebin.com/raw/FF6Vec6B') 
     .then(response => self.setState({ movies: response.data })); 
} 

また、あなたはとして、コンストラクタ内であなたの関数をバインドすることができます。あなたは、コンストラクタでstateを初期化する必要があり、一般的には

、その後、 コールsetStateは、あなたはそれを変更したいとき:

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

documentから:代わりにこれを行います。

関連する問題