【发布时间】:2017-01-03 20:45:17
【问题描述】:
在我们的 Redux Form 5.3(不是 6.x)应用程序中,我想像这样渲染一个 <input type="checkbox" />:
// In some cases, fieldHelper.checked is initially undefined. Then, when the
// user clicks one of the checkboxes, fieldHelper.checked is
// explicitly set to true or false. This change from one of the component's
// props being undefined to having a value causes a React warning; see
// http://stackoverflow.com/a/38015169/473792 and
// https://facebook.github.io/react/docs/forms.html#controlled-components
// So to prevent that warning, we do a quick null check on
// fieldHelper.checked and replace it with false explicitly if it is
// undefined before rendering the checkbox.
const fieldHelper = this.props.field['checkbox'];
const checked = fieldHelper.checked || false;
const modifiedFieldHelper = Object.assign({}, fieldHelper);
delete modifiedFieldHelper.checked;
return (
<input
checked={checked}
{...modifiedFieldHelper}
/>
);
}
如评论中所述,在我的测试环境中,this.props.field['checkbox'].checked 在安装<input> 后立即为undefined。结果,当我的测试修改this.props.field['checkbox'].checked 的值时,我收到以下警告:
警告:ApplicantForm 正在更改复选框类型的不受控制的输入以进行控制。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
...除非我将<input> 上的checked prop 明确设置为false 而不是undefined,如我上面发布的代码sn-p 所示。
我想在测试运行之前设置this.props.fields['checkbox'].checked 的初始值,而不是使用此空检查。 I know I can set the initial value of fields in Redux Form. 有没有办法设置一个辅助属性的初始值,比如 Redux Form 也控制的 checked 属性?
【问题讨论】:
-
您是否尝试过使用布尔值?
-
看起来 Redux-Form 目前在处理复选框方面存在一些错误,所以我可能遇到了这个问题:github.com/erikras/redux-form/issues/334
标签: javascript reactjs redux redux-form