Redux-forms支持validation errors and warnings .
错误会显示一条消息并阻止提交表单,而警告只会显示一条消息。
Redux-forms也支持async validation .
我错误地认为异步验证错误和警告会被支持,但事实并非如此。
不幸的是warnings are not officially possible with async validation .
目前需要相当大的努力才能摆脱使用 redux-forms ,所以我试图找到一个足够的解决方法。
一种解决方案是手动向表单添加警告。如果这是可能的,那么异步验证可以大部分正常执行,但在最后设置警告,而不是提供预期的错误对象。
但我查看了文档,似乎没有办法手动添加警告或与此相关的错误。
您将验证函数传递给 specific field , 或 the form as a whole ,这些验证器函数会根据需要由 redux-forms 调用.
所以看起来错误和警告不能直接设置,但也许我们可以手动触发特定字段的重新验证?
不,显然this is also not currently possible .
总结一下:
- 不可能出现异步验证警告。
- 无法为表单手动设置警告。
- 无法手动触发字段的同步验证。
非常欢迎任何建议、见解或更正。
如果我在这些总结点上有任何错误,我会很高兴!
如果我找不到解决方案,那么我将寻找替代库,然后我将开始这项艰巨的任务,即远离 redux-forms .
这无疑是对我的愚蠢假设的一个很好的提醒。
最佳答案
我听从了 Dennie 的建议,并在我的根 reducer 中使用 reducer.plugin()
来监听 redux 表单的异步验证完成操作 @@redux-form/STOP_ASYNC_VALIDATION
和(正确或错误)通过将 action.payload
注入(inject) syncWarnings
将其从错误更改为警告。 Redux-form 然后将其作为 meta.warning
属性传递给该字段。
reducer 代码:
import { reducer as formReducer } from 'redux-form';
...
const errorToWarning = (state, action) => {
/* eslint-disable no-unused-vars, no-case-declarations */
switch (action.type) {
case "@@redux-form/STOP_ASYNC_VALIDATION":
const { asyncErrors, ...noErrors } = state;
const syncWarnings = action.payload || undefined;
return { ...noErrors, syncWarnings };
default:
return state;
}
};
const rootReducer = combineReducers({
form: formReducer.plugin({
FirstForm: errorToWarning,
AnotherForm: errorToWarning
}),
// other reducers
});
export default rootReducer;
组件:
const MyTextField = ({ meta: { touched, error, warning }, ...props }) => {
let cssClass = "";
let errorText = "";
if (touched) {
cssClass = warning ? "warning" : cssClass;
cssClass = error ? "error" : cssClass;
errorText = warning || errorText;
errorText = error || errorText;
}
return (
<TextField
className={cssClass}
hintText={props.hintText || ""}
{...props}
errorText={errorText}
warning={warning}
/>
);
};
我正在使用 Material UI(这是 TextField
的来源,未在导入中显示)。
参见 redux-form docs有关 reducer.plugin()
的更多信息。
关于javascript - 作为异步验证的结果,我如何显示 redux-form 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461100/