简体   繁体   中英

I am trying to add a router to my react app

I have a react component display's a list of titles and when you click on a title at the top of the page the body of the post is displayed. I have the component that display's the body of the post in a different component.

I want to create a Router file that will switch between Post and Posts depending on the id that is givin by the Posts title.

This is my Routes

import React, { memo } from 'react';
import PropTypes from 'prop-types';
import { Route, BrowserRouter } from 'react-router-dom';
import { withRouter } from 'react-router';

import Posts  from './components/posts';
import Post  from './components/post';

// Proptypes definitions to the component.
const propTypes = {
  /** Router location. */
  // eslint-disable-next-line react/forbid-prop-types
  location: PropTypes.object.isRequired,
};

/**
 * Component used to render the app routes.
 *
 * @param {object} props - The component's props.
 * @returns {object} React element.
 */
const Routes = memo(
  (props) => {
    const { location } = props;

    return (
     <BrowserRouter>
  <div>
   <Route path="/" exact component={Posts} />
   <Route path="/post/:id" exact component={Post} />
  </div>
</BrowserRouter>
    );
  },
);

// Component proptypes.
Routes.propTypes = propTypes;

export default withRouter(Routes);

This is my Posts that displayed all the titles and when you click on the title it passes it to Post component to be displayed at the top of the page. I want to change this so that it links and goes to the Post page and passes the id to the post page.

import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import Link from '@material-ui/core/Link';
import useReduxApi from '@cparram/use-redux-api';
import Post from "./post";

const Posts = props => {
  const [api, apiCall] = useReduxApi("posts");

  // Call api on component mount
  useEffect(() => {
    apiCall({
      endpoint: "https://jsonplaceholder.typicode.com/posts"
    });
  }, []);

  const [selectedPostId, setPostId] = useState(null);
  const preventDefault = event => event.preventDefault();
  return (
    <div>
      <h1>Posts</h1>
      <h5>Select one item</h5>
      {!api.fetching &&
        api.data &&
        api.data.map(post => (
          <Link to='/post/id' onClick={preventDefault}>
         <div key={post.id} onClick={() => setPostId(post.id)}>
            {`title: ${post.title}`}
          </div>
          </Link>
        ))}
    </div>
  );
};



export default Posts;

And this is my post

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

import useReduxApi from '@cparram/use-redux-api';

const Post = props => {
  const { id } = props;
  const [{ fetching, data: post }, apiCall] = useReduxApi(`post-${id}`);

  useEffect(() => {
    apiCall({
      endpoint: `https://jsonplaceholder.typicode.com/posts/${id}`
    });
  }, [id]);

  return (
    <div>
      {fetching && `Loading post with id ${id}...`}
      <p>{!fetching && post && `body: ${post.title}`}</p>
      <p>{!fetching && post && `body: ${post.body}`}</p>
    </div>
  );
};



export default Post;

I created a Link in posts to link to my post page but this does not work. I dont tknow if my router is wrong of my link

codesandbox link https://codesandbox.io/s/nervous-wave-1io99

try this:

const Post = props => {
  const [{ fetching, data: post }, apiCall] = useReduxApi();

  useEffect(() => {
   if(props.match.params.id){
    apiCall({
      endpoint: `https://jsonplaceholder.typicode.com/posts/${
        props.match.params.id
      }`
    });
   }
  }, [props.match.params.id]);

  return (
    <div>
      {fetching && `Loading post with id ${props.match.params.id}...`}
      <p>{!fetching && post && `body: ${post.title}`}</p>
      <p>{!fetching && post && `body: ${post.body}`}</p>
    </div>
  );
};

import React, { useEffect, useState } from "react";
// import ReactDOM from "react-dom";
import {Link} from 'react-router-dom';

import useReduxApi from '@cparram/use-redux-api';
// import Post from "./post";

const Posts = props => {
  const [api, apiCall] = useReduxApi("posts");

  // Call api on component mount
  useEffect(() => {
    apiCall({
      endpoint: "https://jsonplaceholder.typicode.com/posts"
    });
  }, []);

  // const [selectedPostId, setPostId] = useState(null);

  return (
    <div>
      <h1>Posts</h1>
      <h5>Select one item</h5>
      {/* {selectedPostId && <Post id={selectedPostId} />} */}
      {api.fetching && "Loading posts ..."}
      {!api.fetching &&
        api.data &&
        api.data.map(post => (
          <Link to={`/post/${post.id}`}>
            {`title: ${post.title}`}
          </Link>
        ))}
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM