渲染表单以输入值:
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获取您的数据,而只是尝试渲染某些内容。
您的状态尚未设置(可能),因此您收到此错误。