2017-02-23 7 views
3

제목에서 알 수 있듯이 JSON에서 가져온 데이터가 들어있는 React 구성 요소를 fetch()를 사용하여로드하려고합니다.React - JSON로드 및 구성 요소 구성

api 호출은 정상적으로 작동하지만 데이터를 렌더링 할 수 없습니다.

class App extends React.Component { 
 
    constructor(props) { 
 
     super(props); 
 

 
     this.state = { 
 
      user: {} 
 
     } 
 
    } 
 

 
    getUserById(uId) { 
 
     fetch(`https://jsonplaceholder.typicode.com/users/${uId}`) 
 
      .then((response) => { 
 
       return response.json() 
 
      }) 
 
      .then((json) => { 
 
       return json; 
 
      }); 
 
    } 
 

 
    componentDidMount() { 
 
     this.setState({ 
 
      user: this.getUserById(4) 
 
     }) 
 
    } 
 

 
    render() { 
 
     return (
 
      <div> 
 
       <h1>User</h1> 
 
       <p>ID: {this.state.user.id}</p> 
 
      </div> 
 
     ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App/>, 
 
    document.getElementById("container") 
 
);
<div id="container"></div> 
 

 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

이 문제 해결에 어떤 생각 : 여기

코드인가?

답변

5

문제는이 라인에 있습니다

<div class="container"></div> 

당신은 classgetElementById하여 점점 정의했다.

다른 변화는, Ajax 호출 정도로 getUserById 즉시 데이터를 리턴하지 않을 것이며, 데이터 서버로부터 리턴 setState 상태 변수 undefined 값을 설정한다 비동기 될 것이다. 이 문제를 해결하려면 setState 응답을 받으면됩니다.

확인이 :

class App extends React.Component { 
 
    constructor(props) { 
 
     super(props); 
 

 
     this.state = { 
 
      user: {} 
 
     } 
 
    } 
 

 
    getUserById(uId){ 
 
     fetch(`https://jsonplaceholder.typicode.com/users/${uId}`) 
 
     .then((response) => { 
 
      return response.json() 
 
     }) 
 
     .then((json) => { 
 
      this.setState({ 
 
       user: json 
 
      }) 
 
     }); 
 
    } 
 

 
    componentDidMount() { 
 
     this.getUserById(4); 
 
    } 
 

 
    render() { 
 
     console.log(this.state.user); 
 
     return (
 
      <div> 
 
       <h1>User</h1> 
 
       <p>ID: hello</p> 
 
      </div> 
 
     ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App/>, 
 
    document.getElementById("container") 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>

: 당신은 당신이 응답을하면 그 때는 내부의 setState를 수행, setState를 내부에 연료 소모량을 호출하는 그래서 대신 ajax 전화를하고 있습니다 , 다음과 같이하십시오 :

.then(json => { 
    this.setState({user: json}); 
}); 
+0

헤헤, 그래. 나는 그걸 스 니펫에 넣었다. 메모가 내 문제를 해결했습니다. 감사합니다! – user3660122

0

내가 할 수있는 문제 EE - 당신 가져 약속은 나의 제안이 약속 콜백 내부 setState를하는 것입니다, 서버에서 가져온 데이터를 반환하지 않으므로처럼은해야 같습니다

getUserById(uId) { 
    fetch(`https://jsonplaceholder.typicode.com/users/${uId}`) 
     .then(result => result.json()) 
     .then(json => { 
      this.setState({user: json}); 
     }); 
} 
componentDidMount() { 
    this.getUserById(4); 
} 
1

는 사용자 개체에 대한 setState를 getUserById 방법을 결합 시도 json 응답.

class App extends React.Component { 
constructor(props) { 
    super(props); 

    this.state = { 
     user: {} 
    } 
this.getUserById = this.getUserById.bind(this); //add this to your constructor 
} 

getUserById(uId) { 
    fetch(`https://jsonplaceholder.typicode.com/users/${uId}`) 
     .then((response) => { 
      return response.json() 
     }) 
     .then((json) => { 
      return json; //setState in here with your ajax request**strong text** 
     }); 
} 

componentDidMount() { 
    this.setState({ 
     user: this.getUserById(4) 
    }) 
} 

render() { 
    return (
     <div> 
      <h1>User</h1> 
      <p>ID: {this.state.user.id}</p> 
     </div> 
    ); 
} 
} 

ReactDOM.render(
<App/>, 
document.getElementById("container") 
0

여러분의 주로 문제는 getUserById 메서드가 아무 것도 반환하지 않는다는 것입니다. 대신에 상태를 설정해야합니다. 그런 다음 주 컨테이너에 주어진 ID에 문제가 있습니다 만, 나는 당신이 발췌문에서만 실수를했습니다.

나는 위의 코드를 테스트 한

, 그것을 시도 :

class App extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      user: null 
     } 
    } 

    getUserById(uId) { 
     fetch(`https://jsonplaceholder.typicode.com/users/${uId}`) 
      .then((response) => { 
       return response.json() 
      }) 
      .then((json) => { 
       return json; 
      }) 
      .then((result) => { 
       this.setState({user: result}); 
      }); 
    } 

    componentDidMount() { 
     this.getUserById(4) 
    } 

    render() { 
     console.log(this.state.user); 
     return (
      <div> 
       <h1>User</h1> 
       <p>{this.state.user != null ? this.state.user.id : 0}</p> 
      </div> 
     ); 
    } 
} 

ReactDOM.render(
    <App/>, 
    document.getElementById("container") 
);