[英]Is there a way to get access to redux-form errors from inside the Container with reduxForm V7?
[英]How to access pristine prop of reduxForm from inside the Redux state?
我在我的表單中使用 redux-form 的Field
的多個實例,並將 redux-form-material-ui 的TextField
作為可渲染組件:
<Field
component={TextField}
floatingLabelText='Title:'
name='title'
/>
當表單所在的組件被 reduxForm() 包裝時,我們會在該組件內獲得props.pristine
、 props.dirty
等。
但是,我想根據pristine
的值在另一個非 reduxForm 組件或 Redux state 中執行一些操作,但我無法這樣做。
我嘗試將它作為道具傳遞給 Field:
<Field
component={TextField}
floatingLabelText='Title:'
name='title'
pristine={props.pristine}
/>
但是pristine
屬性仍然沒有作為道具出現在state.form.formName
中,也沒有作為道具出現在state.form.formName.registeredFields.title
:
問題:
有沒有辦法在另一個組件或 redux state 中獲取我的表單的pristine
屬性?
更新:升級到7.4.2。 解決了問題!
import { connect } from 'react-redux';
import { isPristine } from 'redux-form'
您需要做的:連接到redux-form-state並訪問它
const mapStateToProps = state => ({
isPristine: isPristine('yourFormName')(state), // Checks whole form
isPristine: isPristine('yourFormName')(state, ["fieldName"]), // Checks particular field
}); connect(mapStateToProps)
您可以使用this.props.isDirty訪問它,並將其傳遞給所需的組件。
從中間件處理此問題可能是最簡單的實現,即檢查表單之間的狀態,在發生redux表單更改時檢查form.config.values和form.config.initialValues。
const formMiddleware = () => store => next => action => {
const state = store.getState()
switch(action.type) {
case '@@redux-form/CHANGE':
store.dispatch({ type: UPDATE_OTHER_FORM, message: Object.is(state.form.config.values, state.form.config.initial) });
break;
}
next(action)
}
另一個選擇(基於用例)是通過原始狀態處理表單,並根據prop的狀態更改調用,並將其傳遞給:
<Button
btnName={pristine ? "Action1" : "Action2"}
type="submit"
action={props.handleSubmit(values => {
onSubmit(
pristine ?
{
...values,
call: 'action1'
} : {
...values,
call: 'action2'
}
)
})}
/>
然后,在您的根組件中,您可以將一個方法(在本例中為“ handleSubmit”)傳遞給表單的handleSubmit道具,然后該道具將監視傳入的表單提交,以根據值決定要調用的操作。 例如
handleSubmit = (values) => {
if(values.call === 'action1') {
this.props.actions.action1(values);
} else if(values.call === 'action2') {
this.props.actions.action2(values);
}
}
希望這對您的特定實現有所幫助,即使您正在尋找將原始狀態帶出表格之外的方法。 您也可以通過這些形式將狀態鏈接到其他表單,但是當我查看去年的內容時,根本不可能將狀態推到表單之外。
要訪問另一個組件內的 prestine prop:
如果您使用基於 Class 的組件:
導入所有必要的東西:
Import { connect } from "react-redux";
Import { isPristine } from "redux-form";
在你的 mapStateToProps function 中:
const mapStateToProps = state => ({
pristine: isPristine('yourFormName')(state), // Checks whole form
pristineField: isPristine('yourFormName')(state, ["fieldName"]), // Checks particular field
});
connect(mapStateToProps, mapDispatchToProps)(YourFormComponent)
如果您使用基於功能的組件:
導入所有必要的東西:
import { useSelector } from "react-redux";
import { isPristine } from "redux-form";
在功能組件內部:
const pristine = useSelector((state) => isPristine("formName")(state));
您可以在此處查看redux-form 提供的所有可用選擇器
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.