这是我正在使用Formik和react-bootstrap编写的表单的模板。我发现一个非常奇怪的错误:如果我在构造函数中用伪数据初始化状态,那么它将正常工作;但是,如果我使用componentDidMount
中具有完全相同的数据来调用setState来模拟API调用,则它会严重中断。
具体地说,我发现状态变量alertVehicles
数组的长度可以为非零,但相应的Formik values.alertVehicles
变量可以为空。现在,所写的表单未显示任何复选框。如果我在guard子句中使用alertVehicles
而不是values.alertVehicles
,则它会因错误Cannot read property 'selected' of undefined
而崩溃。
import React, {Component} from 'react';
import Form from 'react-bootstrap/Form';
import { Formik } from 'formik';
import Button from 'react-bootstrap/Button';
class Alerts extends Component {
constructor(props) {
super(props);
this.loadAlertData = this.loadAlertData.bind(this);
this.state = {
alertRecipient: {},
alertId: '',
alertVehicles: []
}
}
componentDidMount(){
this.loadAlertData();
}
loadAlertData(){
// this will be an API call eventually, obviously.
// if this is initialised in the constructor then everything works!
this.setState( {
alertRecipient: {
name: 'Rob',
simNumber: '0123456789',
},
alertId: 1,
alertVehicles: [
{id: 1, vrn: 'vehicle A', selected: true },
{id: 2, vrn: 'vehicle B', selected: false },
{id: 3, vrn: 'vehicle C', selected: true }
]
})
}
render() {
const { alertRecipient, alertId, alertVehicles } = this.state;
return (
<>
<Formik
initialValues={{ alertRecipient, alertId, alertVehicles }}
onSubmit={ values => {
window.alert(JSON.stringify(values))
}
}
render={({values, handleChange, handleSubmit}) => (
<Form onSubmit={handleSubmit}>
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
name="alertRecipient.name"
value={values.alertRecipient.name}
onChange={handleChange}
/>
<Form.Label>Phone number</Form.Label>
<Form.Control
type="text"
name="alertRecipient.simNumber"
value={values.alertRecipient.simNumber}
onChange={handleChange}
>
</Form.Control>
<Form.Label>Vehicles</Form.Label>
{
//get an error if we just use alertVehicles.length here??
values.alertVehicles.length === 0 ? null : alertVehicles.map((veh, index) => (
<Form.Check type="checkbox"
key={veh.id}
label={veh.vrn}
name={`alertVehicles[${index}].selected`}
checked={values.alertVehicles[index].selected}
onChange={ handleChange }
/>
))
}
<Button type="submit">Save</Button>
</Form>
)
}
/>
</>
)
}
}
export default Alerts;
我听不懂
componentDidMount
中设置伪数据时,代码为何起作用values.alertVehicles
与alertVehicles
似乎不同步。在此先感谢您的帮助。
答案 0 :(得分:1)
由于某种原因,这是Formik的默认行为,您需要提供<mat-error>
道具以覆盖它:
https://github.com/jaredpalmer/formik/issues/811