如何将jQuery AJAX调用返回的值赋给类变量?

时间:2016-12-10 19:54:07

标签: javascript ajax reactjs

AJAX调用返回数据但是如何将它分配给类变量以便我可以在另一个方法中使用它?这是我的代码(这是reactjs组件):

import React from 'react';
import jQuery from 'jquery';
import ListPotions from './list_potions';

export default class Potions extends React.Component {
    constructor(props) {
        super(props);
        this.state = {potions: []};
        this.fetchPotions = this.fetchPotions.bind(this);
        this.objToStrMap = this.objToStrMap.bind(this);
    }

    componentDidMount() {
        this.fetchPotions();
    }

    fetchPotions() {
        jQuery.ajax({
            url: this.props.endPoint,
            dataType: 'json',
            cache: false,
            headers: {
                "Authorization": btoa('mixOfRandomPotions')
            },
            success: function(data) {
                let potions = this.objToStrMap(data);
                this.setState({ potions });
            }.bind(this),
            error: function(xhr, status, err) {
                console.error(this.props.endPoint, status,        
                err.toString());
            }.bind(this)
        });
    }

    objToStrMap(obj) {
        let strMap = new Map();
        for (let k of Object.keys(obj)) {
            strMap.set(k, obj[k]);
        }
        return strMap;
    }

    render(){
        console.log(this.potions);
        return (
            <div className="{this.props.className}">
                <ul>
                    {this.state.potions.map((potion) => <ListPotions key="{potion.id}" potion={potion} /> )}
                </ul>
            </div>
        );
    } 
}

正如您所看到的,我将其分配给this.potions,但在render()方法中,该列表为空。

2 个答案:

答案 0 :(得分:1)

this.potions可能已更新,但您的组件未使用新数据重新呈现。在React中,您可以使用statesetState轻松更新组件的内部数据。这是您的代码(简化):

&#13;
&#13;
class Potions extends React.Component {
    constructor(props) {
    super(props);
    this.state = { potions: [] };
    this.fetchPotions = this.fetchPotions.bind(this);
}

componentDidMount() {
    this.fetchPotions();
}

fetchPotions() {
    // not a network request, I just set some sample data. your request would go here.
    const potions = [{ id: 1, name: 'first' }, { id: 2, name: 'second' }];
    // instead of overwriting a variable (e.g. this.potions), we update the state
    // put this into your network request callback!
    this.setState({ potions });
}

render() {
    console.log(this.state.potions);
    return (
        <div className="{this.props.className}">
            <ul>
                {this.state.potions.map((potion) => <li key={potion.id}>{potion.name}</li> )}
            </ul>
        </div>
    );
}
}

ReactDOM.render(<Potions/>, document.getElementById('View'));
&#13;
<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="View"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您应该在数据为空时处理案例

largest(odd, 11);