Ссылка реквизит при прохождении не работает, когда браузер нажимается вперед и назад React router v4 - PullRequest
0 голосов
/ 02 марта 2019

проблема в том, что ... когда вы загружаете '/' домашний компонент загружается и когда вы нажимаете на Темы, я передаю свои данные из ссылки, и данные, показанные в теге h1, поэтому работают нормально .... (отредактировано) проблема однаждыВы нажимаете «Темы» и нажимаете кнопку «Назад», чтобы перейти на главную страницу и снова нажимать впередЯ вижу, что нет данных, которые были переданы из Link?

Я хочу, чтобы данные присутствовали там даже после того, как я вернусь и снова сделаю пересылку

создал здесь небольшой рабочий вариант использования https://codesandbox.io/s/m4lvm46myx

import React, { Component } from "react";
import ReactDOM from "react-dom";

import { BrowserRouter, Route, Link } from "react-router-dom";



const topics = [
  {
    name: "Functional Programming",
    id: "functional-programming",
    description:
      "In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.",
    resources: [
      {
        name: "Imperative vs Declarative programming",
        id: "imperative-declarative",
        description:
          "A guide to understanding the difference between Imperative and Declarative programming.",
        url: "https://tylermcginnis.com/imperative-vs-declarative-programming/"
      },
      {
        name:
          "Building User Interfaces with Pure Functions and Function Composition",
        id: "fn-composition",
        description:
          "A guide to building UI with pure functions and function composition in React",
        url:
          "https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/"
      }
    ]
  }
];

const Resources = ({ match }) => {
  return <div>Resources</div>;
};

const Home = () => {
  return (
    <div>
      <h1>HOME </h1>
    </div>
  );
};

const Topic = ({ match }) => {
  console.log("match", match);
  const topic = topics.find(({ id }) => id === match.params.topicId);
  return (
    <div>
      <h1>{topic.name}</h1>

      <ul>
        {topic.resources.map(sub => (
          <li key={sub.id}>
            <Link to={`/topics/${match.params.topicId}/${sub.id}`}>
              {sub.name}
            </Link>
          </li>
        ))}
      </ul>
      <hr />
      <Route path={`/topics/:topicId/:subId`} component={Resources} />
    </div>
  );
};

const Topics = props => {
  console.log("Topics location props", props.location.name);
  return (
    <div>
      <h1>Link data passed : {props.location.name}</h1>
      <h1>Topics </h1>
      <ul>
        {topics.map(({ name, id }) => (
          <li key={id}>
            <Link to={`/topics/${id}`}> {name}</Link>
          </li>
        ))}
      </ul>
      <hr />
      <Route path={`/topics/:topicId`} component={Topic} />
    </div>
  );
};

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div className="App">
          <h1>Nested Routers Learnings </h1>
          <ul>
            <li>
              {" "}
              <Link to="/">Home</Link>
            </li>
            <li>
              {" "}
              <Link
                to={{
                  pathname: "/topics",
                  name: "Nischith"
                }}
              >
                Topics
              </Link>
            </li>
          </ul>

          <hr />

          <Route exact path="/" component={Home} />
          <Route path="/topics" component={Topics} />
        </div>
      </BrowserRouter>
    );
  }
}

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

1 Ответ

0 голосов
/ 02 марта 2019

Вместо прямой передачи реквизитов, передайте их, сохранив в состоянии родительского компонента класса.

import { createBrowserHistory } from 'history';

const browserhistory = createBrowserHistory();
  • Встроитьэтот объект в теге <Router> в методе render():

    <Router history={browserHistory}>

Полный код: -

import React, { Component } from "react";
import ReactDOM from "react-dom";
//Imported this module for Browser history
import { createBrowserHistory } from "history";
import { Router } from "react-router-dom";

import { Route, Link } from "react-router-dom";

const browserHistory = createBrowserHistory();

const topics = [
  {
    name: "Functional Programming",
    id: "functional-programming",
    description:
      "In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.",
    resources: [
      {
        name: "Imperative vs Declarative programming",
        id: "imperative-declarative",
        description:
          "A guide to understanding the difference between Imperative and Declarative programming.",
        url: "https://tylermcginnis.com/imperative-vs-declarative-programming/"
      },
      {
        name:
          "Building User Interfaces with Pure Functions and Function Composition",
        id: "fn-composition",
        description:
          "A guide to building UI with pure functions and function composition in React",
        url:
          "https://tylermcginnis.com/building-user-interfaces-with-pure-functions-and-function-composition-in-react-js/"
      }
    ]
  }
];

const Resources = ({ match }) => {
  return <div>Resources</div>;
};

const Home = () => {
  return (
    <div>
      <h1>HOME </h1>
    </div>
  );
};

const Topic = ({ match }) => {
  console.log("match", match);
  const topic = topics.find(({ id }) => id === match.params.topicId);
  return (
    <div>
      <h1>{topic.name}</h1>

      <ul>
        {topic.resources.map(sub => (
          <li key={sub.id}>
            <Link to={`/topics/${match.params.topicId}/${sub.id}`}>
              {sub.name}
            </Link>
          </li>
        ))}
      </ul>
      <hr />
      <Route path={`/topics/:topicId/:subId`} component={Resources} />
    </div>
  );
};

//Recieve the state
class Topics extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: this.props.location.state.name
    };
  }
  render() {
    console.log("Hi");
    console.log("Topics location props", this.state.name);
    return (
      <div>
        <h1>Link data passed : {this.state.name}</h1>
        <h1>Topics </h1>
        <ul>
          {topics.map(({ name, id }) => (
            <li key={id}>
              <Link to={`/topics/${id}`}> {name}</Link>
            </li>
          ))}
        </ul>
        <hr />
        <Route path={`/topics/:topicId`} component={Topic} />
      </div>
    );
  }
}
//Create state, include variable in it and send it.
class App extends Component {
  state = {
    name: ""
  };
  render() {
    return (
      <Router history={browserHistory}>
        <div className="App">
          <h1>Nested Routers Learnings </h1>
          <ul>
            <li>
              {" "}
              <Link to="/">Home</Link>
            </li>
            <li>
              {" "}
              <Link
                to={{
                  pathname: "/topics",
                  state: { name: "Nischith" }
                }}
              >
                Topics
              </Link>
            </li>
          </ul>

          <hr />

          <Route exact path="/" component={Home} />
          <Route path="/topics" component={Topics} />
        </div>
      </Router>
    );
  }
}

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