首页 > 解决方案 > 您将如何重组此验证程序?

问题描述

我有一个父子组件结构,并且在用于子组件的组件目录结构中有一个单独的RequiredFieldValidator 组件。RequiredFieldValidator 可以完美运行,但 React 会在子组件中首次使用 RequiredFieldValidator 时输出以下警告:

警告:在现有状态转换期间无法更新(例如在 内render)。渲染方法应该是 props 和 state 的纯函数。在RequiredFieldValidator

您将如何重组此验证器以保持功能但避免警告?这是代码:

import * as React from "react";
import { Colors } from '@commonResources/colorVariables';

interface IComponentProps {
    fieldId: string,
    fieldName: string,
    triggers: boolean[],
    validationAggregationRoutine: Function,
    validationAggregation: Map<string, boolean>,
    style?: Object,
};

export class RequiredFieldValidator extends React.Component<IComponentProps>{

    constructor(props: IComponentProps) {
        super(props);
    }

    render() {
        const {
            fieldId,
            fieldName,
            triggers,
            validationAggregation,
            style
        } = this.props;

        let isValid = !triggers.includes(true);

        // need to propogate field isvalid ref to the top parent so details are propogated from top to bottom 
        this.props.validationAggregationRoutine(fieldId, isValid);

        // above code will update state and next passthrough will flow through to this next check
        if (validationAggregation.size > 0 && validationAggregation.get(fieldId) == false) {
            isValid = false;
        }

        if (isValid) return null;
        const message = `${fieldName} is required`;

        return (
            <tr>
                <td></td>
                <td></td>
                <td style={{ color: Colors.digitalRed130 }}>
                    <div style={style}>{message}</div>
                </td>
            </tr>
        )
    }
}

标签: reactjs

解决方案


推荐阅读