有什么办法可以保存 onChange 的值吗?

is there any way to save the value of onChange?

我有一个关于 onChange 的问题,所以我试图从我的 onChange 中获取一个值并将其发送到 (''http://localhost:3000/search''),但是当我按下 (Enter) 键时,它进入该页面但最终删除了我的 onChange 的值返回未定义,有没有办法保存我的 onChange 并发送到另一个页面?没有重新给我 undefined

我的代码:

function handleKeyPress(event: any) {
        if(event.keyCode === 13){
          open('http://localhost:3000/search')
        }
      }

    function search(e: any) {
    
        axios.get("http://localhost:3001/search", {params: {q: e.target.value}})
    
    }
    
    return(
        <>
            <div className={styles.Header}>

                <input name='q' type="text" placeholder='Buscar' onChange={(e)=>search(e)} onKeyDown={(e)=>handleKeyPress(e)}/>

                <div></div>
            </div>
        </>
    )

使用 setTimeout 因为搜索功能可能还没有加载

setTimeout(open('http://localhost:3000/search'), 500)

如果您想使用 window.openthis answer 应该会有所帮助。

否则,我建议您使用 react-router 的 useNaviage. You can pass your search param in search property, and access the param on the target page using useParams

import { useNavigate, createSearchParams } from "react-router-dom";

...

const navigage  = useNavigate()
function handleKeyPress(event: any) {
  if(event.keyCode === 13){
    navigage(
      `${"/search"}?${createSearchParams({q: e.target.value})}`
    );
  }
}

...

在“/搜索”页面

 let { q } = useParams();

Here如何为您的项目设置react-router