【问题标题】:Bookmarking the url with the search result使用搜索结果为网址添加书签
【发布时间】:2020-06-30 07:05:12
【问题描述】:

方法:

onSearch(searchString) {
    if (this.props.history) {
      this.props.history.push(
        "/details?search=" + encodeURIComponent(searchString)
      );
    }
  }

搜索栏:

<Search
                  onKeyPress={(event) => {
                    if (event.key === "Enter") {
                      this.onSearch(event.target.value);
                    }
                  }}
                />

onSearch 方法打开此 url:http://localhost:3000/marketPlace/details?search=iphone 并以“iphone”显示所有结果。我想要的是,每当用户将此网址添加书签时,他应该返回到与搜索结果为 iphone 相同的页面。我不知道该怎么做,谁能帮我解决这个问题

【问题讨论】:

  • 您是说当您直接访问 url 时(通过在浏览器 URL 栏中输入并按 Enter 键,即发出 http 请求),您希望应用程序以与您相同的状态显示使用 onSearch 方法导航到这条路线?这取决于您的应用程序的设置,但您可能需要查看 React Router reacttraining.com/react-router/web/guides/quick-start。您可以使用它来将您的应用程序的 url 与一个状态相匹配,并指示应用程序根据 url 的内容加载特定的 React 组件。
  • 是的,当此网址通过聊天或电子邮件共享时,用户希望登陆同一页面

标签: javascript reactjs typescript search


【解决方案1】:

假设您正在编写一个客户端应用程序并且您不需要在服务器端呈现搜索结果,React Router (npm react-router-dom) 将使您能够根据请求的 url 重新创建应用程序的特定状态.

您应该能够按照 React Router 文档将路由器应用于现有应用程序:https://reacttraining.com/react-router/web/guides/quick-start

这是一个与您的用例类似的非常简单的路由器示例。

例子表明:

  • / 的请求将呈现“主页”组件。
  • /search?term=iphone 的请求将呈现“SearchResults”组件,而this.searchTerm 将等于字符串iphone
  • SearchResults 组件从 url 解析查询字符串并识别搜索词。在示例中,这只是显示给最终用户,但您可以使用它来获取您的搜索结果,例如使用fetch()

您可以使用两个文件重现该示例:

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import {
  BrowserRouter as Router,
  Switch,
  Route
} from 'react-router-dom';

class SearchResults extends React.Component {
  constructor(props) {
    super(props);
    let queryString = new URLSearchParams(props.location.search);
    this.searchTerm = queryString.get('term');
  }

  render() {
    return <p>Search results page for term: { this.searchTerm }</p>;
  }
}

function App() {

  return (
    <Router>
      <Switch>

        <Route path="/search" component={SearchResults} />

        <Route path="/">
          <p>Homepage</p>
        </Route>

      </Switch>
    </Router>
  );

}

ReactDOM.render(<App />, document.getElementById('root'));

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="index.js"></script>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多