gpt4 book ai didi

javascript - react : REST redirect failing

转载 作者:行者123 更新时间:2023-12-01 00:01:16 25 4
gpt4 key购买 nike

有一个文本字段,其中有一个事件处理程序,当按下[Enter Key]时要提交。


const [ query, setQuery ] = React.useState('')
...
<TextField
label="Search Codebase"
id="queryField"
onChange={ event => setQuery(event.target.value)}
onKeyDown={handleKeyDown}
/>

这是按键处理函数

  const handleKeyDown = e  => {
if (e.key === 'Enter') {
console.log('moving to: /search/' + query); // query here = `TextField value`
window.location.href = '/search/' + query; // query here = '?'
}
}

结果 URL 为 => /search/?
URL 应该是 => /search/TextField 的内容

最佳答案

您可以使用 react-router-dom 中的 history 对象,并使用查询参数进行重定向,如下所示:

  import React, { Fragment, useState} from "react";
import { useHistory } from 'react-router-dom';

const history = useHistory();

const handleKeyDown = e => {
if (e.key === 'Enter') {
console.log('moving to: /search/' + query); // query here = `TextField value`
history.push({
pathname: '/search',
search: query // Should be of the form `?${param}=${value}`
})
}
}

了解有关历史对象的更多信息 here .

关于javascript - react : REST redirect failing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60706301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com