如何在Next.js中通过链接发送数据?

huangapple go评论79阅读模式
英文:

How to send data through Link in Next/JS?

问题

我的下一个版本是13.1.5。我正在尝试通过我的组件中的 Link 发送 contact.name。最佳方法是什么?Link 的第一段代码只是我的原始代码。

<Link
    className={styles.summaryLink}
    href={`${routes.accountShow(contact.number)}/contacts`}
>
    {contact.name}
</Link>

第二段是我尝试使用 pathnamequery 做的,但是当我这样做时,它不断报错,说 href 需要是一个 string,而且URL也变成了 /contacts/[object,object]。如果可能的话,我也不想在URL中显示 contact.name

<Link
    className={styles.summaryLink}
    href={{
        pathname: `${routes.accountShow(contact.number)}/contacts`,
        query: { contactName: contact.name },
    }}
>
    {contact.name}
</Link>
英文:

My Next version is 13.1.5. I am trying to send contact.name through the Link in my component. Whats the best way to do this? The first code of the Link is just my original code.

      &lt;Link
          className={styles.summaryLink}
          href={`${routes.accountShow(contact.number)}/contacts`}
        &gt;
          {contact.name}
      &lt;/Link&gt;

This second is what I tried to do with pathname and query but when I do this it keeps giving an error saying href needs to be a string and the url also goes to /contacts/[object,object]. I am also not trying to show contact.name in the url at all if possible.

   &lt;Link
      className={styles.summaryLink}
      href={{
        pathname: `${routes.accountShow(contact.number)}/contacts`,
        query: { contactName: contact.name },
      }}
    &gt;
      {contact.name}
    &lt;/Link&gt;

答案1

得分: 1

在这一点上,你可能会发现上下文很有帮助。React上下文允许在组件之间共享定义的数据。

在你的情况下,你可以这样实现它:

import { createContext } from 'react';

const ContactContext = createContext();

export default ContactContext;

然后在你的根组件中,你必须创建上下文提供程序:

import ContactContext from './ContactContext';

function MyApp({ Component, pageProps }) {
  const [contactName, setContactName] = useState(null);

  return (
    <ContactContext.Provider value={{ contactName, setContactName }}>
      <Component {...pageProps} />
    </ContactContext.Provider>
  );
}

export default MyApp;

在这一点上,我们已经定义了contactName状态并将值和设置函数传递给创建的上下文。每个组件现在都可以设置MyApp组件的状态。

在导航部分,然后必须相应地设置上下文。然后,您可以通过useContext钩子访问相应的函数以及值本身:

import { useContext } from 'react';
import { useRouter } from 'next/router';
import ContactContext from './ContactContext';

function YourComponent({ contact }) {
  const { setContactName } = useContext(ContactContext);
  const router = useRouter();

  const handleClick = (e) => {
    e.preventDefault();
    setContactName(contact.name);
    router.push(`${routes.accountShow(contact.number)}/contacts`);
  };

  return (
    <a
      className={styles.summaryLink}
      href={`${routes.accountShow(contact.number)}/contacts`}
      onClick={handleClick}
    ></a>
  );
}

显示组件也可以通过useContext钩子读取值,然后相应地显示数据:

import { useContext } from 'react';
import ContactContext from './ContactContext';

function ContactPage() {
  const { contactName } = useContext(ContactContext);

  return <div>Contact Name: {contactName}</div>;
}

但是要小心,如果你使用大量基于上下文的组件,代码很快就会变得难以维护。我建议你考虑用一种ID替代名称,并将其定义为路由的一部分。

英文:

You might find a context helpful at this point.A React Context allows defined data to be shared across components.
In your case you could implement it as follows

import { createContext } from &#39;react&#39;;

const ContactContext = createContext();

export default ContactContext;

in your root component you must then create the context provider

import ContactContext from &#39;./ContactContext&#39;;

function MyApp({ Component, pageProps }) {
  const [contactName, setContactName] = useState(null);

  return (
    &lt;ContactContext.Provider value={{ contactName, setContactName }}&gt;
      &lt;Component {...pageProps} /&gt;
    &lt;/ContactContext.Provider&gt;
  );
}

export default MyApp;

at this point we have defined the state contactName and pass the value and the set function to the created context.
Each component can now set the state of the MyApp component.

in the area of your navigation, you would then have to set the context accordingly. You can then access the corresponding function as well as the value itself via the useContext hook

import { useContext } from &#39;react&#39;;
import { useRouter } from &#39;next/router&#39;;
import ContactContext from &#39;./ContactContext&#39;;

function YourComponent({ contact }) {
  const { setContactName } = useContext(ContactContext);
  const router = useRouter();

  const handleClick = (e) =&gt; {
    e.preventDefault();
    setContactName(contact.name);
    router.push(`${routes.accountShow(contact.number)}/contacts`);
  };

  return (
    &lt;a
      className={styles.summaryLink}
      href={`${routes.accountShow(contact.number)}/contacts`}
      onClick={handleClick}
    &gt;
    &lt;/a&gt;
  );
}

The display component can also read the values via the useContext hook and then display the data accordingly.

import { useContext } from &#39;react&#39;;
import ContactContext from &#39;./ContactContext&#39;;

function ContactPage() {
  const { contactName } = useContext(ContactContext);

  return &lt;div&gt;Contact Name: {contactName}&lt;/div&gt;;
}

but a little warning. If you use a lot of context based components, code becomes very quickly bad maintainable. I would give you the idea to replace the name with a kind of ID and define it as part of the route.

答案2

得分: 1

第一个是正确的。
但你应该使用 to 属性而不是 href

让我分享更新后的代码:

     &lt;Link
          className={styles.summaryLink}
          to={`${routes.accountShow(contact.number)}/contacts`}
        &gt;
          {contact.name}
      &lt;/Link&gt;
英文:

The first one is correct.
But you should use to attribute instead of href.

Let me share the updated code

     &lt;Link
          className={styles.summaryLink}
          to={`${routes.accountShow(contact.number)}/contacts`}
        &gt;
          {contact.name}
      &lt;/Link&gt;

huangapple
  • 本文由 发表于 2023年7月13日 19:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定