2017-11-22 5 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

업데이트는 아약스 요청을 다음과 같이 : 당신이 잘못된 위치에 초기 상태를 넣어

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에서 대신이 작업을 수행합니다.

관련 문제