我使用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的新手,我希望你能帮我,
谢谢。
发布于 2020-01-14 09:22:19
这是非常正常的,因为您从customerData
函数中返回了一个承诺。我会这样解决你的问题:
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
dataCustomer: [],
}
this.initCustomerData()
}
async initCustomerData() {
this.setState({
customerData: await customerData()
})
}
发布于 2020-01-14 09:21:01
您的customerData只会返回需要解决的承诺。这一承诺正被设定在dataCustomer
中。
您可以做的是,在另一个方法中调用方法customerData
,该方法可以从constructor
或任何其他生命周期方法中触发。解析承诺,然后调用setState
方法来设置所需的值。
发布于 2020-01-14 09:27:22
constructor(props) {
super(props);
this.state = {
reactTable: reactTableData(),
reactBootstrapTable: reactBootstrapTableData(),
};
this.initCustomerData();
}
initCustomerData = () => {
customerData().then((data) => {
this.setState({ dataCustomer: data })
});
}
https://stackoverflow.com/questions/59730685
复制相似问题