【发布时间】:2022-01-10 20:15:21
【问题描述】:
如何在不更改 URL 的情况下呈现动态路由器组件?
我有 SearchInput 组件,我在项目的多个地方使用它
const SearchInput = (props) =>{
const [value, setValue] = useState('');
const submit = () =>{
//How can I render the dynamic component and when the SSR fetch request is done update the URL
const router = useRouter();
return router.push(`/search/${value}`); //this way is chaning the URL :(
}
return (
<>
<input value={value} onChange={(e)=>setValue(e.target.value)} />
<button onClick={}>Search</button>
</>
)
}
export default SearchInput;
这是嵌套的 SSR 动态路由器,看起来像这样
pages/search/[searchValue].js
export const search = async (searchValue) => {
//this request retun a URL that needs to be shown in the browser
//How can I change the URL here?
const users = await axios.post(`/API/search`, {search: searchValue}).then(({data}) => {
return data
})
return users
}
const SearchResult = ({downloads}) =>{
return (
<>
<SearchInput />
<section>
{downloads.map((row)=>{
return <h1>{row.title}</h1>
})}
</section>
</>
)
}
export default SearchResult;
export const getServerSideProps = async (context) => {
const { searchValue } = context.query;
const res = await search(searchValue);
return {
props: {
downloads: res,
url: res.link
}
}
}
由于我使用的是服务器端渲染,所以我想知道如何先获取请求然后更改 URL?
当前的方法是有效的,但它首先更改 URL,然后呈现嵌套组件。我想要实现的是首先呈现 SSR 组件并获取请求然后更改 URL。这可能吗?
【问题讨论】:
标签: reactjs next.js server-side-rendering