Prop mismatch server/client,如何生成持久存在的唯一ID?

Prop mismatch server/client, how to generate a unique ID that persists?

我正在使用 ReactJS.net 进行服务器渲染。我想制作一个简单的组件,输出一个标签和一个输入,其中标签通过 htmlFor 属性 引用输入。由于此组件可以在同一页面上多次使用,因此我需要它为组件的每个实例提供唯一的 ID。

因此,我在构造函数中生成了一个 guid 并使用它 - 它工作正常,除了在服务器端和客户端生成 ID,这会导致值不匹配。

如何解决这种不匹配问题?

示例代码:

interface IProps { whatever:string }

export default class Test extends React.Component<IProps> {
    private _guid: string;

    constructor(props: IProps) {
        super(props);
        this._guid = Utils.getGuid(); // generates a new guid
    }

    render(): JSX.Element {
        return (
            <div>
                <label htmlFor={this._guid}A nice label</label>
                <input id={this._guid} type="text" />
            </div>
        );
    }
}

代码将 运行 运行但会生成警告:

警告:道具 htmlFor 不匹配。服务器:“87d61dbe-b2a8-47bd-b299- c6e80445f626" 客户端:"f0297b42-7781-48a4-9904-75b8fd2d1140"

您必须根据传递给组件的道具构建一个 ID - 在这种情况下,您可以使用 whatever 字符串创建哈希码。

我想出了解决办法:

为标签和输入元素创建一个引用。在 componentDidMount() 生命周期函数中,将 "id" 和 "htmlFor" 分配给具有生成值的这些元素。

componentDidMount() {
    this._labelRef.htmlFor = this._guid;
    this._inputRef.id = this._guid;
}

现在 this._guid 从服务器到客户端仍然是两个不同的值,但 React 不会对此发出警告,因为我在 Mount 之后应用这些值。