[英]Cannot populate input from Axios after Call API
将表单呈现为输入值:
return (
handleSubmit将检查表单是否有效并准备好提交,它会调用回调函数// //在本例中为onSubmit()
The name property specifies what piece of state is being edited
<Field
label="Email"
type="email"
name="Email"
component={this.renderField}
/>
<Field name="city"
label="Cidade"
value={this.state.value}
onChange={this.handleChange}
options={options}
component="select">
</Field>
<Field
label="Password"
type="password"
name="password"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
<Link to="/register" className="btn btn-danger">Already registered?</Link>
</form>
);
我从json获取值,但该字段为空
您的初始状态可能未设置,因此this.state.cities
实际上为空。
在渲染函数中执行以下操作:
render() {
const options = ( this.state.cities || [] ).map( (city) => ( {
value: city.name,
label: city.id
} );
return (
-- other components --
{ options.length ? (
<Field name="city"
label="Cidade"
value={this.state.value}
onChange={this.handleChange}
options={options}
component="select"
/>
) : null }
-- other components --
);
}
( this.state.cities || [] )
将检查this.state.cities
是否可用,否则它将使用空数组。
更多细节:axios调用是异步的。 这意味着,React不等待axios来获取您的数据,而只是尝试呈现某些内容。
您的状态尚未设置(可能),因此出现此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.