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 中,您可以使用 state
和 setState
轻松更新组件的内部数据。这是您的代码(简化):
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/