在我的主 App.js componentDidMount()
生命周期阶段,我有一个axios get请求到休息服务 .
编辑:包括完整 UserForm.js
class App extends Component {
// default state object
constructor() {
super();
this.state = {
schemas: []
}
}
componentDidMount() {
axios
.get('http://localhost:port/querier/api/rest/dataschema/list')
.then(response => {
console.log(response)
this.setState({
schemas: response
});
})
.catch(error => console.log(error.response));
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">App</h1>
</header>
<LinkButton />
<UserForm schemas={this.state.schemas} />
</div>
);
}
}
此请求成功返回控制台消息中的模式(字符串)数组(现在只有1)
Response:
{
"data": [
"Phone Record"
],
"status": 200,
"statusText": "OK"
如何使用axios get请求返回的 Phone Record
填充此 UserForm.js
下拉列表
import React from 'react';
import PropTypes from 'prop-types';
class UserForm extends React.Component {
constructor() {
super();
this.state = {schemas: []};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.data});
}
handleSubmit(event) {
alert('The dataschema you picked is: ' + this.state.schemas);
event.preventDefault();
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pick the dataschema to describe your data file:
<select value={this.state.value} onChange={this.handleChange}>
{
(schemas && schemas.length > 0) && schemas.map((schema) => {
return (<option value="${schema.value}"> {schema.name}</option>);
})
}
</select>
</label>
</form>
</div>
);
}
}
export default UserForm;
2 回答
我相信你正在寻找这样的东西,其中模式被传递给UserForm,而select的选项是动态呈现的 . 对于上下文,我已经填写了更多的代码片段 .
UPDATED :我在代码片段中修复了一些拼写错误,并为您提供了一种处理未定义模式的方法 .
NOTE :这应该引导你朝着正确的方向前进,你应该能够接受这个答案,并完成你的工作 .
将记录传递给UserForm的解决方案