簡體   English   中英

Next.js: Router.push with state

[英]Next.js: Router.push with state

我正在使用 next.js 重建用於服務器端渲染的應用程序。 我有一個處理搜索請求的按鈕。

在舊應用程序中,處理程序是這個:

search = (event) => {
    event.preventDefault();
    history.push({
        pathname: '/results',
        state: {
            pattern: this.state.searchText,
        }
    });
}

在結果 class 中,我可以使用 this.props.location.state.pattern 獲得 state 日期。

所以現在我使用 next.js:

import Router, { withRouter } from 'next/router'

performSearch = (event) => {
    event.preventDefault();
    Router.push({ pathname: '/results', state: { pattern: this.state.searchText } });
};

在結果 class 中,我使用

static async getInitialProps({req}) {
    return req.params;
}

我不確定是否必須將其添加到我的 server.js 中:

server.get('/results', (req, res) => {
    return app.render(req, res, '/results', req.params)
})

但是,function getInitialProps 會拋出錯誤,因為 req 未定義。 長文短問:如何在不使用 GET 參數的情況下將 state 或 params 傳遞到另一個頁面?

next.js您可以像這樣傳遞查詢參數

Router.push({
    pathname: '/about',
    query: { name: 'Someone' }
})

然后在您的下一個頁面(此處位於/about頁面)中,通過router道具檢索query ,需要使用withRouter將其注入到Component

import { withRouter } from 'next/router'

class About extends React.Component {
  // your Component implementation
  // retrieve them like this
  // this.props.router.query.name
}

export default withRouter(About)

如果您希望您的 url 保持干凈,請像下面這樣對 Prithwee Das 的回答做一點補充。

Router.push({
    pathname: '/about',
    query: { name: 'Someone' }
}, '/about');

現在您可以使用 props 訪問組件中的 props

...

const YourComponent = (props) => {
    useEffect(() => {
        console.log(props.router.query.name);
    }, [props.router.query]);

    return (
        <React.Fragment>
            ...
        </React.Fragment>
    );
};

...

我不知道這是否支持 SSR,但我必須按以下方式進行操作以避免錯誤cannot read property 'query' of undefined

這使用useRouter鈎子來訪問 url,如下導入。

import { useRouter } from 'next/router'

假設您要將數據{name:'Someone'}Component A傳遞到Component B

Component A中,

const router = useRouter();

router.push(
  { pathname: "/path_of_component_b", query: { name: "Someone" } },
  "path_of_component_b"
);

Component B中,

const router = useRouter();

useEffect(() => {
  alert(router.query.name); // Alerts 'Someone'
}, [router.query]);

如果您想要“干凈”的 url,一種方法是將 onClick 處理程序添加到您的鏈接並將所需信息存儲在上下文/redux 存儲中。 如果你已經有了,它很容易實現。

<Link href='...'>
  <a onClick={()=>{dispatch(....)}}>Link<a/>
<Link>

使用最新版本的 NextJS 我們有hooks ,在我們的例子中是useRouter

import { useRouter } from 'next/router'

function ActiveLink({ children, href }) {
  const router = useRouter()

  const handleClick = (e) => {
    e.preventDefault()
    router.push(href)
  }

  return (
    <a href={href} onClick={handleClick}>
      {children}
    </a>
  )
}

export default ActiveLink

如果你想要一個動態根,就像把它放在字符串參數中一樣簡單:

<button type="button" onClick={() => router.push('/post/abc')}>
  Click me
</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM