利用localStorage来记录输入框的历史输入

241 阅读1分钟

//基于react //使用mantine组件库

export default function Index(){
    const [input, setInput] = useState();
    //定义一个空数组
    const [list, setList] = useState<string[]>([])
    const fetchData = () => {
        //浅拷贝list
        const newList = [...list] 
        //将输入框的内容添加到数组中,获得新的数组
        newList.push(input);
        //将newList中的数据同步
        setList(newList);
        //向内存中存储一个key为app-name,value为newList的数据
        localStorage.setItem('app-name',JSON,stringify(newList)); 
    }

    useEffect(() => {
        //刚进页面,去取key为app-name对应的值,并将其放到list中
        const appList:string[] = JSON.parse(localStorage.getItem('app-name' || '[]'));
        setList(appList);
    }, [])
    return(
        <>
        //将appList作为下拉框的数据,输入框中的值改变的时候,将改变的值赋值给input
            <Select 
                data={appList}
                value={input}
                onChange={(value)=>{
                    setInput(value || '')
                }}
             />
        </>
    ) 
}