【问题标题】:Ajax Api call in React JsxReact Jsx 中的 Ajax Api 调用
【发布时间】:2017-06-26 13:25:01
【问题描述】:

大家好,我正在尝试使用 ajaxJSX ,可以在 DOM 中使用 .append() 吗?

示例代码:

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;

【问题讨论】:

  • 不要将jQuery 仅用于其 AJAX 模块。查看专门的 HTTP 客户端,例如 axios
  • 你为什么要在 React 中这样做?只需更新状态并在渲染方法中显示即可。
  • 没有办法使用Ajax?

标签: javascript jquery ajax reactjs jsx


【解决方案1】:

你为什么要在 React 中这样做?

这不是更干净吗?

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.

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2020-05-27
    • 2019-02-14
    • 2021-12-11
    • 2021-12-21
    • 1970-01-01
    • 2017-03-10
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多