reactjs 使用SolidJS将搜索到的图书信息传递到另一个组件

kognpnkq  于 2023-04-29  发布在  React
关注(0)|答案(1)|浏览(135)

我正在开发一个Web应用程序,你搜索一本书,这本书的一些信息,如流派,可用性,描述和作者将显示在另一个屏幕上。
到目前为止一切正常,当我搜索一本书时,它的所有信息都显示在控制台中,但我不能在另一个页面中显示这些信息。我使用Solid Router并尝试了许多不同的方法来做到这一点,但它就是不起作用(我也尝试使用 prop 来做到这一点,但它没有再次工作)。
下面是您搜索图书的组件(仅显示在控制台中)
SearchBooks.jsx

import axios from "axios";
import { createSignal } from "solid-js";
import Books from './Books'
function SearchBooks() {
  const [searchText, setSearchText] = createSignal("");
  const [book, setBook] = createSignal([]);
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.get(
        `https://www.googleapis.com/books/v1/volumes?q=${searchText()}`
      );
      if (response) {
        const books = response.data.items;
        console.log(books);
        setBook(response.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="w-full mt-10 bg-gray-100 flex justify-center items-center">
      <div className="container mx-auto dark:bg-gray-900 rounded-lg p-14">
        <form onSubmit={handleSubmit}>
          <h1 className="text-center font-bold text-white text-4xl">
            Find your perfect books{" "}
          </h1>{" "}
          <br />
          <div className="sm:flex items-center bg-white rounded-lg overflow-hidden px-2 py-1 justify-between">
            <input
              className="text-base text-gray-400 flex-grow outline-none px-2"
              type="text"
              placeholder="Search for books"
              value={searchText()}
              onInput={(e) => setSearchText(e.target.value)}
            />
            <div className="ms:flex items-center px-2 rounded-lg space-x-4 mx-auto ">
              <button className="dark:bg-gray-900 text-white text-base rounded-lg px-4 py-2 font-thin">
                Search
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

export default SearchBooks;

那么,我如何才能使这些信息显示在另一个页面/组件?

kqhtkvqz

kqhtkvqz1#

这是因为当您切换页面时数据会被丢弃。更改路径会挂载所选路径的组件,卸载前一个路径的组件,即您从中获取数据的组件。可能有很多解决方案,但最简单的一种是使用资源从路径组件外部获取数据,并将其传递到任何您喜欢的地方。
另一种解决方案是使用Context API,获取值并将其推送到上下文并在另一个页面中使用它,但上下文提供程序应该位于path的组件之外,以便数据不会被丢弃。
另一种选择是将book信号保持在路由上方的范围内,并传递getter和setter。

相关问题