组件未在React Router上渲染

时间:2019-05-11 19:49:12

标签: reactjs react-router

我创建了一个卡片组件,然后单击“ Click”(我想渲染一些文章),我正在尝试使用react,但是我不知道我的代码有什么问题(我是初学者)。

当我单击该URL时,其行为与我的文章ID一致,但该页面为空白,并且控制台上没有任何内容(甚至我的console.log)


class JobCard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      isLoading: true
    };
  }

  componentWillMount() {
    fetch(url)
      .then(data => data.json())
      .then(result =>
        this.setState({
          data: result,
          isLoading: false
        })
      );
  }

  render() {
    if (this.state.isLoading === true) return <LoadingSpinner />;
    else {
      const { match } = this.props;
      return (
        <>
          <div>
            {data.map(job => (
              <div>
                <div key={job._id} className="blog-card">
                  <div className="meta"
                          <Link
                            to={{
                              pathname: `${match.url}/${job._id}/${
                                job.position_name
                              }`,
                              state: job
                            }}
                          >
                            {job.workplace_name}
                          </Link>{" "}
                          Job Restaurant
                        </span>
                      </p>
                    </p>
                  </div>
                </div>

                <Route path={`${match.path}/:id`} component={Articles} />
              </div>
            ))}
          </div>
          )}
          <Footer />
        </>
      );
    }
  }
}

export default JobCard;

未呈现的文章组件:

import React from 'react'

const Articles = ({ location }) => (
    <div>
      <h1>{location.state.restaurant}</h1>
      <h2>{location.state.article}</h2>
      {location.state.position_name}
      <h4>Hello</h4>
    </div>
  )

  export default Articles;

Ant the App.js


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

import JobCard from "./components/Cards/JobCard";

class App extends Component {
  render() {
    return (
      <div>
      <div>
        hello World
      </div>
        <ul>
          <li>
            <Link to="/JobCard">JobCard</Link>
          </li>
        </ul>

        <Route exact path="/JobCard" component={JobCard} />
      </div>
    );
  }
}

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

export default App;

1 个答案:

答案 0 :(得分:0)

您要在JobCard组件的data.map循环内定义Articles路线。它应该在循环之外。这在您的情况下引起问题。