Реакция роутера 4 Пример параметров запроса не работает - PullRequest
0 голосов
/ 10 декабря 2018

проблема : попытка реализовать пример параметров запроса реагирующего маршрутизатора в моей локальной среде.код ниже с их сайта.

import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";

function ParamsExample({ location }) {
  let params = new URLSearchParams(location.search);

  return (
    <Router>
      <div>
        <p>
          React Router does not have any opinions about how your parse URL query
          strings. Some applications use simple key=value query strings, but
          others embed arrays and objects in the query string. So it's up to you
          to parse the search string yourself.
      </p>
        <p>
          In modern browsers that support{" "}
          <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">
            the URL API
        </a>
          , you can instantiate a <code>URLSearchParams</code> object from{" "}
          <code>location.search</code> and use that.
      </p>
        <p>
          In{" "}
          <a href="https://caniuse.com/#feat=url">
            browsers that do not support the URL API (read: IE)
        </a>{" "}
          you can use a 3rd party library such as{" "}
          <a href="https://github.com/sindresorhus/query-string">query-string</a>.
      </p>
        <div>
          <h2>Accounts</h2>
          <ul>
            <li>
              <Link to={{ pathname: "/account", search: "?name=netflix" }}>
                Netflix
            </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=zillow-group" }}>
                Zillow Group
            </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=yahoo" }}>
                Yahoo
            </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=modus-create" }}>
                Modus Create
            </Link>
            </li>
          </ul>

          <Child name={params.get("name")} />
        </div>
      </div>
    </Router>
  );
}

function Child({ name }) {
  return (
    <div>
      {name ? (
        <h3>
          The <code>name</code> in the query string is "{name}"
        </h3>
      ) : (
          <h3>There is no name in the query string</h3>
        )}
    </div>
  );
}

export default ParamsExample;

при рендеринге я получаю следующее сообщение об ошибке
TypeError: Cannot read property 'search' of undefined
, что довольно прямолинейно, но когда я делаю location.search в моем consoleя получаю следующий вывод "?name=zillow-group"
с учетом того, что location.search является допустимым свойством, но не уверен, почему реакция не видит его.

1 Ответ

0 голосов
/ 10 декабря 2018

Когда вы регистрируете местоположение в консоли, вы регистрируете объект window.location.В вашем компоненте, однако, есть определенная опора местоположения, которая имеет приоритет.Это явно не показано в примере реакции-маршрутизатора , но они где-то рендерит компонент ParamsExample и передают в подпор местоположения.

Вы можете получить доступ к подпункту местоположения реактора-маршрутизатора (среди прочего) либо с помощью withRouter hoc , либо с помощью компонента маршрута .Вот пример :

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";

function ParamsExample() {
  return (
    <Router>
      <div>
        <p>
          React Router does not have any opinions about how your parse URL query
          strings. Some applications use simple key=value query strings, but
          others embed arrays and objects in the query string. So it's up to you
          to parse the search string yourself.
        </p>
        <p>
          In modern browsers that support{" "}
          <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL">
            the URL API
          </a>
          , you can instantiate a <code>URLSearchParams</code> object from{" "}
          <code>location.search</code> and use that.
        </p>
        <p>
          In{" "}
          <a href="https://caniuse.com/#feat=url">
            browsers that do not support the URL API (read: IE)
          </a>{" "}
          you can use a 3rd party library such as{" "}
          <a href="https://github.com/sindresorhus/query-string">
            query-string
          </a>
          .
        </p>
        <div>
          <h2>Accounts</h2>
          <ul>
            <li>
              <Link to={{ pathname: "/account", search: "?name=netflix" }}>
                Netflix
              </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=zillow-group" }}>
                Zillow Group
              </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=yahoo" }}>
                Yahoo
              </Link>
            </li>
            <li>
              <Link to={{ pathname: "/account", search: "?name=modus-create" }}>
                Modus Create
              </Link>
            </li>
          </ul>

          <Route
            render={({ location }) => {
              let params = new URLSearchParams(location.search);
              return <Child name={params.get("name")} />;
            }}
          />
        </div>
      </div>
    </Router>
  );
}

function Child({ name }) {
  return (
    <div>
      {name ? (
        <h3>
          The <code>name</code> in the query string is "{name}"
        </h3>
      ) : (
        <h3>There is no name in the query string</h3>
      )}
    </div>
  );
}

function App() {
  return <ParamsExample />;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...