簡體   English   中英

道具不匹配服務器/客戶端,如何生成唯一的持久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之后應用這些值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM