2017-06-26 48 views
-1

大家好我想用ajaxJSX,可以在DOM中使用.append()嗎?Ajax Api調用React Jsx

示例代碼:

var React = require('react');  
var t = require('./../../../translations/translate'); 
var LocationComponent = React.createClass({ 

    componentDidMount: function() { 
     $(document).ready(function() { 
      $.ajax({ 
       type: 'GET', 
       url: 'www.api.com', 
       data: {}, 
       dataType: 'json', 
       success: function (data) { 
        console.log(url); 
        $.each(data, function (index, element) { 

         // se serve il loop 
         var HTML = element.name; 

         $('#div').append(HTML); 

        }); 
       } 
      }); 
     }); 

    }, 
    render: function(){ 

     return(

      <div id="div"></div> 
     ) 
    } 
}); 

module.exports = LocationComponent; 
+0

不要使用'jQuery'只是它的AJAX組件。看看一個專門的HTTP客戶端,如['axios'](https://github.com/mzabriskie/axios) – glhrmv

+0

你爲什麼要在React中這樣做?只需更新狀態並在渲染方法中顯示即可。 – Boky

+0

有沒有辦法使用Ajax? – Lib3r74

回答

1

你爲什麼要這麼做的反應是?

這是不是更清潔?

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

     this.state = { 
     isLoading: true, 
     data: [] 
     } 
    } 

    componentDidMount(){ 
     fetch('https://facebook.github.io/react-native/movies.json') 
     .then((response) => response.json()) 
     .then((responseJson) => { 
      this.setState({data: responseJson.movies, isLoading: false}); 
     }) 
     .catch((error) => { 
      console.error(error); 
     }); 
    } 

    render(){ 
     if(this.state.isLoading){ 
     return (<div>Loading...</div>) 
     } 
     return (
     <div> 
      {this.state.data.map(item => <div>{item.title}</div>)} 
     </div> 
    ) 
    } 
} 

React.render(<Test />, document.getElementById('container')); 

Here is the fiddle.