我有一个axios get请求,该请求返回一个字符串数组。
class App extends Component {
// default state object
constructor() {
super();
this.state = {
data: []
};
}
componentDidMount() {
axios
.get("/dataschema/list")
.then(response => {
console.log(response);
this.setState({ data: response });
})
.catch(error => console.log(error.response));
}
}
当我发出此请求时,Web控制台会显示响应的data
部分
Response:
{
"data": [
"Phone Record"
],
}
我的问题是如何获取此字符串并用它填充下拉列表?
对于上下文,整个响应如下所示:
{data: Array(1), status: 200, statusText: "OK", headers: {…}, config: {…}, …}
data:Array(1)
0: "Phone Record"
length:1
__proto__: Array(0)
在我的UserForm.js
类中,我通过模式作为道具
render() {
const { schemas } = this.props; //schemas references the list received from response and passed as a prop
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick the dataschema to describe your data file:
<select schemas={this.schemas} onChange={this.handleChange}>
{schemas &&
schemas.length > 0 &&
schemas.map(schema => {
return <option value="${schema.schemaName}"> </option>;
})}
</select>
</label>{" "}
<br />
</form>
</div>
);
}
如何处理响应数据以使用返回的字符串填充下拉列表?
编辑:数据的新形状
Response:
{
"data": [
{
"name": "Phone Record"
}
],
答案 0 :(得分:1)
App.js 由于响应是一个巨大的对象,并且您只关心数据(数组),因此仅将数据存储为状态的一部分是很有意义的。
componentDidMount() {
axios
.get("/dataschema/list")
.then(response => {
console.log(response);
this.setState({ data: response.data });
})
.catch(error => console.log(error.response));
}
UserForm.js 元素“ option”允许一个子元素作为其value属性的掩码,因此设置value属性不会设置option的子元素的值(在您的代码中,您仅设置了该值,而没有设置option的子元素)>
render() {
const { schemas } = this.props; //schemas references the list received from response and passed as a prop
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick the dataschema to describe your data file:
<select onChange={this.handleChange}>
{schemas &&
schemas.length > 0 &&
schemas.map(schema => {
return <option key={schema} value={schema}>{schema}</option>;
})}
</select>
</label>{" "}
<br />
</form>
</div>
);
}