我构建了一个 api,它返回我在数据库中注册的单位,但在尝试返回这些单位时没有进行审查
import React, { Component } from 'react';
import axios from 'axios';
const api = {
units: () => {
axios.get('http://192.168.0.23/api/public/api/units')
.then(response => {
console.log(response);
return response.data.data
}).catch((error) => {
console.log(error.message)
});
return 'Error'
},
};
export default api;
响应正确显示数据,response.data.data
如果在具有类的文件中使用,我可以设置状态units = []
并使用setState
返回单位
但是,我想为 api 返回创建此文件,但是由于我不使用类,所以我知道我无法使用状态。
有没有办法让类不返回这些数据,或者保留在变量或类似的东西中?
或者在没有类的情况下直接使用setState
?
我相信这些将是解决我的问题的方法,但如果其他人不知道将 api 调用与最终类放在同一个文件中也可能是这样。
我也试过这样:
async function getUnits() {
return await axios.get('http://192.168.0.23/api/public/api/units');
}
getUnits.then((response) => {
console.log(response);
return response.data.data
}).catch((response) => {
console.log(response)
});
但是错误表明getUnits.then不是一个函数
即使使用正常功能也不起作用:
function units() {
axios.get('http://192.168.0.23/api/public/api/units')
.then(response => {
console.log(response);
return response.data.data
}).catch((error) => {
console.log(error.message)
});
return 'Error'
};
最佳答案
使用下面的代码,它会对你有所帮助。
通常我们只会加载数据,然后渲染我们的应用程序。但 React 期望所有数据都有一些初始状态,并且需要在 AJAX 请求完成后自行更新。因此,您需要将所有数据存储在应用程序的状态中。
看起来是这样的:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import axios from 'axios';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {units: []};
}
componentDidMount() {
this.getUnits();
}
getUnits() {
axios.get('http://192.168.0.23/api/public/api/units')
.then(response => {
this.setState({ units: response.data.data }));
}).catch((error) => {
console.log(error.message)
});
}
render() {
const unit = this.state.units.map((item, i) => (
<div>
<h1>{ item.example }</h1>
</div>
));
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Units: {unit}</Text>
</View>
);
}
}
如果您希望子组件将该数据传递给。看起来像这样:
const unit = this.state.units.map((item, i) => (
<div>
<h1>{ item.example }</h1>
<Test unitData={item} />
</div>
));
在不同的测试
组件中
class Test extends Component { //use the data in a class component
constructor(props) {
super(props);
}
render() {
const unit = this.props.unitData
return (
<div className="test">
<h1>{unit.example}</h1>
</div>
);
}
}
请查看 here 的示例,这将帮助您解决问题。
示例:
希望这对你有帮助!!
关于reactjs - 尝试在没有类的情况下返回 api 数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47757385/