2017-03-15 2 views
0

API를 가져 와서 응답을받는 반응 애플리케이션을 만들었습니다. 코드는 다음과 같습니다.함수에 대한 API 응답 및 컨트롤 채우기

export class EmpDetails extends React.Component { 
    constructor(props) {   
    super(props); 
    this.state = {}; 

    this.updateEmpName = this.updateEmpName.bind(this); 
    } 

    componentWillReceiveProps(nextProps) {  
    this.handleProp(nextProps); 
    if(nextProps){ 
     this.GetData(nextProps); 
    } else { 
     console.log("Emp number not set"); 
    } 
    } 

    GetData(props, EmpCollection) { 
    this.ApiCall(props);  
    } 

    ApiCall(props) { 
    $.ajax({ 
     url: 'http://localhost:8081/getdata',  
     type: 'POST', 
     data: {Empnumber:props.Empnumber}, 
     success: function(data) { 
     this.setState({EmpCollection: data.EmpCollection}); 
     }.bind(this), 
     error: function(xhr, status, err) { 
     console.error(this.props.Empnumber, status, err.toString()); 
     }.bind(this) 
    }); 
    } 

    getInitialState(){ 
    return { 
     EmpCollection: [] 
    } 
    } 

    updateEmpName(e) { 
    this.setState({EmpName: e.target.value}); 
    } 

    render() { 
    return (
     <form> 
     <div > 
      <input 
      type="text" 
      id="EmpName" 
      placeholder="Emp Name" 
      value={this.state.EmpName} 
      onChange={this.updateEmpName} /> 
     </div> 
     </form> 
    ); 
    } 
} 

응답을받을 수 있으며 render()에만 사용할 수 있습니다. GetData() 또는 다른 메소드에서 API 응답을 원했기 때문에 컨트롤의 상태를 설정하고 컨트롤을 채울 수 있습니다. 렌더링되지 않습니다. 어떤 생각이 내가 어떻게 이것을 얻을 수 있습니까?

+0

- 이제 어떻게 적 방법이 ApiCall 그냥 이런 식으로 사용하도록 할

. 당신은 데이터 가져 오기 함수가 당신의 구성 요소가 아닌 액션에 있어야합니다. – Borjante

+0

ok ...하지만 여기서는 배열에 데이터를 저장하고 있습니다. 또한 아약스에서 올바른 응답을 얻을 수 있습니다. 왜 내가 redux를 사용해야합니까? – user2768132

+0

redux를 사용할 필요가 없습니다. 특히 단순한 경우에 특히 그렇습니다. Redux는 앱이 더 커질 때 (구성 요소 내부의 데이터 가져 오기 처리가 유지 불가능한 혼란이 됨) 큰 시간을 소비하는 추가 복잡성을 추가합니다. 그러나 간단한 작업의 경우 일반 응답을 사용하고 구성 요소로 데이터 가져 오기를 사용하는 것이 좋습니다. – OlliM

답변

0

그럼 응답을 어딘가에 저장해야합니다. 구성 요소 외부의 변수 일 수도 있고 구성 요소 속성 일 수도 있습니다. 예를 들어,

class YourComponent extends React.Component { 
 

 
    constructor() { 
 
    // your code ... 
 
    this.response = null; 
 
    } 
 
    
 
    callApi() { 
 
    const self = this; 
 
    
 
    $.ajax({ 
 
     // your code ... 
 
     success: function(response) { 
 
     self.response = response; 
 
     } 
 
    }) 
 
    } 
 
    
 
    someOtherMethod() { 
 
    console.log(this.response) 
 
    } 
 

 
}

+0

내 코드에서 배열 EmpCollection을 선언했습니다. 나는 다른 변수를 저장해야합니까? – user2768132

+0

아니요,하지만'EmpCollection' 배열을'consctructor' 함수 안에 선언해야합니다. 'getInitialState'는 es5 구문을위한 메소드입니다 (React.createClass()). – disstruct

0

나는에 추천 문서 반응 당신이 componentDidMount하지 componentWillReceiveProps의 수명주기 방식의 API를 호출을하는 것이 좋습니다 것입니다.

API 호출 방법을 약간 변경해야합니다.

ApiCall(props) { 
    return $.ajax({ 
     url: 'http://localhost:8081/getdata',  
     type: 'POST', 
     data: {Empnumber:props.Empnumber} 
    }).fail((responseData) => { 
     if (responseData.responseCode) { 
      console.error(responseData.responseCode); 
     } 
    }); 
} 

기본적으로 위의 호출은 나중에 사용할 수있는 jquery 약속을 반환합니다. 당신은 아마 REDUX 워드 프로세서 throught를 이동해야

GetData(props,EmpCollection) 
{ 
    this.ApiCall(props) 
     .then(
      function(data){ 
       console.log(data); 
       // set the state here 
      }, 
      function(error){ 
       console.log(error); 
      } 
    );  
} 
관련 문제