React 18 useId 不能在键中

错误:无法在回调中调用 React Hook “useId”。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用。那么,问题,我们可以在哪里使用 useId()?我还使用代码为我的映射 div 获得了相同的 id:

// @ts-ignore
import React, {useRef, useState, useId} from 'react';

interface InputLocationProps {
    cleanAddress(): void
}

export const InputLocation: React.FC<InputLocationProps> = ({cleanAddress}) => {
    const id = useId()
    const ref = useRef<HTMLInputElement>(null);
    const [text, setText] = useState<string>('');
    const [textArray, setTextArray] = useState<string[]>(['more']);
    const changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
        setText(event.target.value)
    }
    const putTextInArray = (puttingText: string) => {
        setTextArray(prevState => [ ...prevState, puttingText])
    }
    const keyPressHandler = (event: React.KeyboardEvent<HTMLInputElement>) => {

        if (event.key === 'Enter') {
            event.preventDefault();
            putTextInArray(text)
            console.log(ref.current!.value)
            ref.current!.value = '';
            setText('');
            cleanAddress();
        }
    }
    return (
        <form>
            <label htmlFor="count">{text}</label>
            <input ref={ref} onChange={changeHandler} onKeyPress={keyPressHandler} type="text" id="count"/>
            {textArray.map(textArrayItem => {
                return <div key={useId()}>{textArrayItem}</div>
            })}
        </form>
    );
};
stack overflow React 18 useId cannot be in key
原文答案
author avatar

接受的答案

根据 documentation

const Component = () => {
  // outside callback
  const id = useId();

  return array.map((item, index) => <div key={`${id}-${index}`}>some content</div>
}

答案:

作者头像

useIdNOT 用于在列表中生成密钥。密钥应该从您的数据中生成。