Mag*_*gas 11 reactjs react-native
我建立了一个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;
Run Code Online (Sandbox Code Playgroud)
响应正确显示数据,response.data.data如果在具有类I的文件中使用if ,则可以设置状态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)
});
Run Code Online (Sandbox Code Playgroud)
但错误表明了这一点 getUnits.then is not a function
即使具有正常功能也不起作用:
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'
};
Run Code Online (Sandbox Code Playgroud)
使用以下代码,它将为您提供帮助。
通常,我们只是加载数据,然后渲染我们的应用程序。但是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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
并且如果您希望子组件将数据向下传递给。看起来像这样:
const unit = this.state.units.map((item, i) => (
<div>
<h1>{ item.example }</h1>
<Test unitData={item} />
</div>
));
Run Code Online (Sandbox Code Playgroud)
在不同的Test组成部分
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
请在此处检查示例,这将帮助您解决问题。
例子:
希望能帮到你!!
| 归档时间: |
|
| 查看次数: |
1344 次 |
| 最近记录: |