我在React项目中使用Formik库。以我的formik形式,我想有条件地初始化值。如果是插入操作,而不是我想要将下拉列表的第一个值设置为默认值,而如果是更新操作,那么我想从反应状态分配这些值。
下面是我的代码:
constructor(props) {
super(props);
this.state = {
data:{
studentId : ''
}
}
};
render() {
const studentList = this.props.studentList && this.props.studentList;
<Formik
initialValues={this.state.data}
enableReinitialize={true}
onSubmit={this.formSubmit}
>
{({ values, setFieldValue }) => (
<Field component={Select} name="studentId"
options={studentList}
value={studentList.filter(option => option.value == values.studentId)}
onChange={(opt) => {
setFieldValue("studentId", opt.value);
}}
/>
)}
</Formik>
}
现在,如果是插入操作,则应将学生ID设置为学生列表中的第一条记录;如果是更新操作,则学生ID将已经存在于this.state.data;中。我已采用一个表示操作类型的变量。因此,我不必担心知道当前的操作类型。我尝试在formik的initialValues内部调用函数,但是没有用。我无法在render内设置状态,这将导致连续循环。那么如何在Formik中实现这一目标呢?