[Udemy] searching xx -3

이진경·2020년 5월 22일
0

Udemy

목록 보기
3/7
post-thumbnail

response받은 후 컴포넌트 state를 렌더링 한 다음 출력할 수 있게 설정하려면.

=> 당장은 가져온 이미지의 갯수를 보여주고 싶다.

  • so to add in state to my app component i need to first initialize my state at the top of this class
class App extends React.Component {

// 1. we want to make proper name of state as images..also these images expect 
to contain an array. so, default value=> []

  state = {
    images: [],
  };
  
  async onSearchSubmit(anything) {
    const response = await axios.get('https://api.unsplash.com/search/photos', {
      params: { query: anything },
      headers: {
        Authorization: 'Client-ID Rw6et1-um043INr5rEgB3uiIeQHs_6LlF5UMrDcEUws',
      },
    });
    
// 2. after making a request over to unsplash we get the response we pull out the actual results or the list of images.

    this.setState({ images: response.data.results });
  }
  render() {
    return (
      <div className="ui container" style={{ marginTop: '10px' }}>
        <SearchBar onSubmit={this.onSearchSubmit} />
        
        // 3. i want to print out the number of images that we fetched.
        && here is another reason to default our images property to be array.
        if we had defaulted it to be null when we tried to access this statement         images at length we would have seen an error message and said can't     		access property length of null. so another good reason to default that to 		be an array.
         
        Found :{this.state.images.length} images
      
      </div>
    );
  }
}
export default App;
  • 하지만 상위처럼 하면 하기와 같은 error 가 뜬다

  • console.log(this)

  • we've got a callback func.(async onSearchSubmit(anything))
    this is a callback func onsearchsubmit that we passed down to some child component that searchbar component.
    searcbar component is then going to call that function at some point in time in the future.

결과적으로 app에서 console찍은 this는 searchbar안의 onsubmit을 가르키게 됨.
이걸 고치려면 arrow funtion을 onSearchSubmit으로 감싸주어야함.

0개의 댓글