[英]unique key props with Formik Fields
I am mapping some text fields like this:我正在映射一些这样的文本字段:
{
AddVehicleFields.map(({formikRef, ...input}) => (
<>
<TextField
key={formikRef}
helperText={
getIn(formik.touched, formikRef)
? getIn(formik.errors, formikRef)
: ''
}
error={
getIn(formik.touched, formikRef) &&
Boolean(getIn(formik.errors, formikRef))
}
value={getIn(formik.values, formikRef)}
{...input}
variant="outlined"
margin="normal"
onChange={(props) => {
formik.handleChange(props);
formik.handleBlur(props);
}}
onBlur={formik.handleBlur}
/>
<br />
</>
));
}
where the fields look like this:字段如下所示:
export const AddVehicleFields: Array<FormField> = [
{
id: 'freeSeats',
name: 'freeSeats',
formikRef: 'freeSeats',
label: 'Free Seats',
},
{
id: 'numberPlate',
name: 'numberPlate',
formikRef: 'numberPlate',
label: 'Number Plate',
},
I am already passing a key
to each element but I still get index.js:1 Warning: Each child in a list should have a unique "key" prop.
我已经向每个元素传递了一个key
,但我仍然得到index.js:1 Warning: Each child in a list should have a unique "key" prop.
元素index.js:1 Warning: Each child in a list should have a unique "key" prop.
What should I try to fix this?我应该尝试什么来解决这个问题?
The key
needs to be on the outer most element. key
需要在最外面的元素上。 The one that encapsulates all the children.一个封装了所有的孩子。 In this case, it's a React fragment.在这种情况下,它是一个 React 片段。 So change it to this:所以把它改成这样:
{AddVehicleFields.map(({ formikRef, ...input }) => (
<React.Fragment key={formikRef}>
<TextField
helperText={
getIn(formik.touched, formikRef)
? getIn(formik.errors, formikRef)
: ''
}
error={
getIn(formik.touched, formikRef) &&
Boolean(getIn(formik.errors, formikRef))
}
value={getIn(formik.values, formikRef)}
{...input}
variant="outlined"
margin="normal"
onChange={props => {
formik.handleChange(props);
formik.handleBlur(props);
}}
onBlur={formik.handleBlur}
/>
<br />
</React.Fragment>
))}
You need to move key in the child to the root component您需要将子组件中的键移动到根组件
{
AddVehicleFields.map(({formikRef, ...input}) => (
// add key here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<div key={formikRef}>
<TextField
helperText={
getIn(formik.touched, formikRef)
? getIn(formik.errors, formikRef)
: ''
}
error={
getIn(formik.touched, formikRef) &&
Boolean(getIn(formik.errors, formikRef))
}
value={getIn(formik.values, formikRef)}
{...input}
variant="outlined"
margin="normal"
onChange={(props) => {
formik.handleChange(props);
formik.handleBlur(props);
}}
onBlur={formik.handleBlur}
/>
<br />
</div>
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.