我有两个函数,一个函数从用户那里获取输入,另一个函数执行搜索提供的输入数据。我想在 searchQuery
函数内使用 useState
中的 getServerSideProps
。
有没有办法做到这一点?
function SearchDemo() {
const [searchQuery, setSearchQuery] = useState('')
const ChangeHandler = event => {
setSearchQuery(event.target.value)
}
const ButtonHandler = event => {
event.preventDefault()
console.log(`Data: ${searchQuery}`)
}
return (
<div>
<form onSubmit={ButtonHandler}>
<div>
<label>Search:</label>
<input type="text" name="search" value={searchQuery} onChange={ChangeHandler}/>
<button>Search</button>
</div>
</form>
</div>
);
}
export async function getServerSideProps({query: {page}, searchQuery}){
console.log(searchQuery)
return {
props: {
data: data
}
}
}
答案 0 :(得分:1)
您需要推送 url 并重新加载页面,因为它是服务器端渲染的。
const router = useRouter()
const ButtonHandler = event => {
event.preventDefault()
router.push(`/thecurrentUrl?search=${searchQuery}`
// if doesn't work then use window.location.href
console.log(`Data: ${searchQuery}`)
}
export async function getServerSideProps({query: {page}, searchQuery}){
console.log(query.search)
return {
props: {
data: data
}
}
}