javascript - 如何将 jQuery AJAX 调用返回的值分配给类变量?

标签 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() 方法中,列表为空。

最佳答案

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

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'));
<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>

关于javascript - 如何将 jQuery AJAX 调用返回的值分配给类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079652/

相关文章:

javascript - Internet Explorer 对象预期错误

javascript - 为什么当我在最后一个 else 语句中更改 slaying 时,浏览器会崩溃

javascript - 使用 JS/Jquery 检测 URL 的更改(不仅仅是哈希)

php - Jquery ajax php 需要帮助请

jquery - 如何解析ajax请求的json响应?

javascript - 是否有存储 ReactJS Hook 文件的最佳实践?

php - 设备方向和分页

JavaScript 持续检查复选框是否被选中

reactjs - 将应用程序从react-azure-adb2c移植到react-aad

javascript - 使用 NextJS 和 highcharts-react-official 的气泡图