javascript - 从 axios 请求返回字符串数组填充反应下拉列表
问题描述
我有一个 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"
}
],
解决方案
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 属性不会设置选项子级的值(在您的代码中,您只是设置值而不是选项的子级)
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>
);
}
推荐阅读
- jquery - 试图通过悬停或鼠标悬停和-out来实现jquery“盲目”效果,但到目前为止还没有运气。有任何想法吗?
- python - 我有两个列表,我需要从一个列表中选择一个随机样本,然后从第二个列表中选择相应的索引
- java - 如何修复此代码中的重播功能?
- javascript - Cloud Functions 无法从实时数据库中获取令牌
- c++ - 如何`static_assert`在成员初始化列表中构造模板类?
- vhdl - 我无法通过端口映射理解的 sintaxis 错误
- java - Android泄露服务连接
- java - 我在安装库时遇到问题
- c++ - 返回 unique_ptr 私有成员数据而不转移所有权
- bash - 为什么 bash 会破坏 MPI 作业控制循环