简体   繁体   English

我正在尝试向我的 React 应用程序添加路由器

[英]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.我想创建一个路由器文件,该文件将根据 Posts 标题给出的 id 在 Post 和 Posts 之间切换。

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.这是我的帖子,显示了所有标题,当您单击标题时,它会将其传递给 Post 组件以显示在页面顶部。 I want to change this so that it links and goes to the Post page and passes the id to the post page.我想更改它,以便它链接并转到帖子页面并将 id 传递到帖子页面。

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代码和框链接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>
  );
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我无法使用反应路由器路由我的应用程序? - Why am I not able to route my app using react router? 我正在尝试在我的反应应用程序中添加图标,但此方法不起作用需要帮助和指导 - I am trying to add icons in my react app but this method not working Need help and guidance 我正在尝试在我的 React Hangman App 中为一组字母设置动画 - I am trying to animate an array of letters in my React Hangman App 我正在尝试通过 express 为我的 React 应用程序提供服务,为什么我会收到 404? - I'm trying to serve my react app from express, why am I getting a 404? 为什么我没有重定向到我选择的路径? 反应路由器 - Why am I not being redirect to my selected path? React Router 我正在尝试使用 next.js 转换我现有的 React 应用程序。 这是正确的做法吗? - I am trying to convert my existing react app with next.js. Is it a right thing to do? 我正在尝试在我的 react redux 应用程序中使用 map。 但使用useDispatch后,控制台显示错误 - I am trying to use map in my react redux app. but after using useDispatch, the console is showing error 我正在尝试创建一个反应网站并在其中添加挂钩,但面临这个错误 - I am trying to create a react website and add hooks in it but face this erros 我应该在React Router之外的URL中添加参数吗? - Should I add Parameters to my URL outside of React Router? 如何在我的反应路由器代码中添加错误页面? - How do i add an error page to my react router code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM