我正在学习 React,我用 Form 制作了一个页面。
这个表单应该通过 axios 从后端获取数据。 我需要帮助,因为无论我做什么,数组都不会显示在选择选项中。
数据示例:
[{"国家": "德国""代码": 112 }]
import React, { Component } from 'react';
import { Row, Col, Button, Form } from 'react-bootstrap';
import axios from 'axios';
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
country: []
};
}
componentDidMount() {
axios
.get('URL')
.then((response) => {
console.log(response);
this.setState({
country: response
});
})
.catch((error) => console.log(error.response));
}
handleChangeCountry = (event) => {
this.setState({ country: event.target.value });
};
inputCountryHandler = (event) => {
this.setState({
input: {
country: event.target.value
}
});
};
render() {
// const { country} = this.state;
return (
<Form className="calculator-table">
<Form.Group controlId="first-row" className="Focus-line">
<Form.Label>Country</Form.Label>
<Form.Control
as="select"
className="User-Input"
placeholder=""
value={this.state.country}
onChange={this.handleChangeCountry}
id="country"
option={this.country}
/>
</Form.Group>
);
}
}
export default Form;
我希望数组数据显示在下拉选择中。
谢谢你的回答
最佳答案
您应该首先解析来自 API 的 JSON 响应。
componentDidMount() {
axios
.get('URL')
.then((response) => {
console.log(response);
this.setState({
country: JSON.parse(response) //parse the response
});
})
.catch((error) => console.log(error.response));
}
关于javascript - 如何解析从后端到下拉列表的结果 React axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765003/