导航到另一个页面时下一个/链接丢失状态

fre*_*erk 8 javascript reactjs next.js react-state

我正在开发一个Next.js 应用程序。出于此问题的目的,我的应用程序中有两个页面:列出所有书籍的BooksPage和呈现书籍详细信息的BookPage 。就组件而言,我有一个<Books />组件可以<Book />为我的图书馆数据库中的每本书呈现一个组件。

这是我的组件:

图书.js

function Books({ books }) {
  return (
    <>
      {books.map(book => (
        <Book key={book.id} book={book} />
      ))}
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

书.js

class Book extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = { liked: false };
  }

  like = () => {
    this.setState({ liked: this.state.liked ? false : true })
  };

  render() {
    return (
      <>
        <Link href={`/books/${book.slug}`}>
          <a>{book.title}</a>
        </Link>

        <Button onClick={this.like}>
          <LikeIcon
            className={this.state.liked ? "text-success" : "text-dark"}
          />
        </Button>
      </>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

问题:

假设我在BooksPage页面上。当我单击图标颜色的“喜欢”按钮时,<Book />图标颜色会在前端正确切换,并且在后端成功添加或删除“喜欢”。当我刷新BooksPage时,所有状态都保持一致。

当我喜欢BooksPage上的某些内容,然后立即导航到BookPage而不使用下一个/链接刷新时,就会出现问题。那里的“喜欢”按钮没有一致地切换,并且BooksPage的状态丢失。请注意,如果我硬刷新页面,一切都会恢复正常。

缓慢的解决方案:不要使用 next/link。

代替

<Link href={`/books/${book.slug}`}>
  <a>{book.title}</a>
</Link>
Run Code Online (Sandbox Code Playgroud)

<a href={`/books/${book.slug}`}>{book.title}</a>
Run Code Online (Sandbox Code Playgroud)

快速解决方案:继续使用下一个/链接吗?

有没有办法在导航到另一个预渲染路线时使用 next/link 并保持状态?

fre*_*erk 1

通过 API 以某种方式传递liked书籍的属性。然后,将该 prop 从一个组件传递Books到另一个Book组件。

componentDidUpdate()向您的书籍组件添加一个方法。

class Book extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = { liked: this.props.liked };
  }

  componentDidUpdate(prevProps) {
    if (this.props.liked !== prevProps.liked) {
      this.setState({
        liked: this.props.liked,
      });
    }
  }

  like = () => {
    this.setState({ liked: !this.state.liked })
  };

  render() {
    return (
      <>
        <Link href={`/books/${book.slug}`}>
          <a>{book.title}</a>
        </Link>

        <Button onClick={this.like}>
          <LikeIcon
            className={this.state.liked ? "text-success" : "text-dark"}
          />
        </Button>
      </>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)