我试图从api中调用数据/数组,并使用<Text>显示,但是输出是空白。
我也尝试过这个"this.setState({ menu_name: json.ordName })",但是--它只需要获取一个数据。我的目标是去取一个数组。
这是我的密码
settlement.js
constructor(props){
super(props)
this.state = {
....
menu_name: []
tbl: this.props.navigation.state.params.tbl,
};
}
fetchOrdName = async () => {
const response = await fetch("http://192.168.254.100:3308/OrdName/ordName/" + this.state.tbl )
const json = await response.json()
this.setState({ menu_name: json })
}
componentDidMount() {
this.fetchOrdName();
.....
}
render() {
return (
<View>
<FlatList
.....
<View>
<Text>Name: { this.state.menu_name.ordName }</Text>
....
</View>
/>
<View/>
)}我的后端:
OrdName.js (模型)
var Task = {
OrdName:function(id,callback) {
return db.query("SELECT menu_name AS ordName FROM orders where tbl_id=?",[id],callback);
},
}OrdName.js (路线)
var Task = require('../models/OrdName');
router.get('/ordName/:id?', (req, res, next) => {
Task.OrdName(req.params.id,function(err,rows){
if(err)
{
res.json(err);
}
else{
res.json(rows);
}
});
});截图:
将数据发送到api

从api接收数据

我的邮递员的作品:

应显示此名称。
api中的两个数据。

发布于 2018-10-31 08:53:29
fetch("http://192.168.254.100:3308/OrdName/ordName/" + this.state.tbl )
.then((response) => response.json())
.then((responseData) => {
this.setState({ menu_name: responseData })
})发布于 2018-10-31 09:22:00
你必须试着用id和parseInt来进行类型转换。
let id =parseInt(this.state.tbl);
fetch(`http://192.168.254.100:3308/OrdName/ordName/${id}`)
.then((response) => response.json())
.then((responseData) => {
this.setState({ menu_name: responseData })
})发布于 2018-10-31 10:11:22
如果我错了,请纠正我,您获取的数据menu_name是一个数组。然后,您应该像<Text>Name: { this.state.menu_name[ 0 ].ordName }</Text>一样访问它的内容,或者像这样循环:
{
this.state.menu_name.map( ( menu ) => {
return ( <Text>{menu.ordName}</Text> )
});
}https://stackoverflow.com/questions/53079374
复制相似问题