gpt4 book ai didi

reactjs - reduxForm - 更新后初始值不适用

转载 作者:行者123 更新时间:2023-12-03 13:35:59 29 4
gpt4 key购买 nike

我使用 Redux 表单版本 6.8.0。

我有一个表单组件,它通过“mapStateToProps”函数获取“initialValues”。在第一次渲染时,一切都工作得很好。

按照我的表单配置:

const CategoryChangeForm = reduxForm({
form: 'change-category',
validate: newCategoryValidate,
enableReinitialize: true
})(CategoryChange);

当我更改字段“类别”并且更新成功时,我会从 firebase 收到新的更新值。我通过提到的“mapStateToProps”函数将此更新值传递给“initialValues”:

function mapStateToProps(state, ownProps) {
return {
initialValues: { category: state.categories[ownProps.id].name, id: ownProps.id }
};
}

预计新值将应用于“类别”字段组件。但它没有获得更新的值。

我的“Field”组件的配置:

const fieldProps = {
category: {
name: 'category',
type: 'text',
placeholder: 'Bezeichnung',
component: InputField
},
hidden: {
name: 'id',
type: 'hidden',
component: 'input'
}
};

这是我的表单组件:

export const CategoryChange = props => {
const {
color,
message,
handleSubmit,
stateComponent
} = props;

console.log("Props: ", props);

return (
<span>
<Subline color={ color } marginTop={ 70 } marginBottom={ 30 } align="center">{ message }</Subline>
<form>
<Field { ...fieldProps.category } />
<Field { ...fieldProps.hidden } />
<Button onClick={ handleSubmit(changeCategory.bind(stateComponent)) }>Ändern</Button>
<Button marginBottom={ 5 } marginTop={ 10 }>Löschen</Button>
</form>
</span>
);
}

我可以观察到更新后,我的表单组件重新渲染了 2 次。第一次它的属性“initialized”被设置为“true”。但第二次它设置为“假”。第二次渲染是由于包装我的表单组件的特殊组件的 stateChange 而发生的。当更新成功时,会触发临时的“setState”并向用户显示适当的消息。但由于第二次渲染,表单组件没有初始化。

如果您需要查看更多代码,请告诉我。

希望有人能解决这个问题......

最佳答案

According to the docs :

By default, you may only initialize a form component once via initialValues. There are two methods to reinitialize the form component with new "pristine" values:

  1. Pass a enableReinitialize prop or reduxForm() config parameter set to true to allow the form the reinitialize with new "pristine" values every time the initialValues prop changes. To keep dirty form values when it reinitializes, you can set keepDirtyOnReinitialize to true. By default, reinitializing the form replaces all dirty values with "pristine" values.

  2. Dispatch the INITIALIZE action (using the action creator provided by redux-form).

您可以将 CategoryChangeForm 从函数更改为类,并从 componentWillReceiveProps 中的 redux-forms 调用 initialize 操作方法。

import {initialize} from 'redux-form'

CategoryChangeForm extends Component {
...
componentWillReceiveProps(nextProps) {
// check the props and call initialize when needed
}
}

mapDispatchToProps = dispatch => ({
initialize: (data) => initialize('change-category', data)
})

关于reactjs - reduxForm - 更新后初始值不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47250306/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com