我使用 ReactJS 和 axios 我试图获取数据客户
反应: 16.5.2
axios: 0.18.0
我有一个带有构造函数的类:
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
dataCustomer: customerData(),
};
方法 customerData():
export function customerData(){
// axios get
return axios.get("my/url")
.then(res => {
let data = res.data.data;
console.log(data);
return data
})
.catch(err => {
console.log(err);
})
}
当我console.log(this.state);
时,我得到了如下的承诺数据:
我对ReactJS还是很陌生,希望您能为我提供帮助,
谢谢。
答案 0 :(得分:2)
这很正常,因为您从customerData
函数返回了一个Promise。我会这样解决您的问题:
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
dataCustomer: [],
}
this.initCustomerData()
}
async initCustomerData() {
this.setState({
customerData: await customerData()
})
}
答案 1 :(得分:0)
您的customerData仅返回需要解决的Promise。该承诺已在dataCustomer
中设置。
您可以做的是,在另一个可以从customerData
或任何其他生命周期方法触发的方法中调用方法constructor
。兑现承诺,然后调用setState
方法来设置所需的值。
答案 2 :(得分:-1)
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
};
this.initCustomerData();
}
initCustomerData = () => {
customerData().then((data) => {
this.setState({ dataCustomer: data })
});
}