【问题标题】:how do i access route that create by app in reactjs我如何访问由应用程序在 reactjs 中创建的路由
【发布时间】:2021-02-01 07:43:03
【问题描述】:

在这里,我通过 api 从服务器获取新闻,然后为该特定新闻项目创建路由。当用户单击其中一个新闻项目时,该路线将创建并且用户将重定向到创建的路线,但是在浏览器中前进和返回时导航存在问题。
我知道我应该创建一个文件来获取路由的参数并再次调用该特定新闻的 api,但我不知道如何帮助我。
这是 News.js 中嵌套路由的代码:
return (
<Router>
  <Switch>
    <Route
      path={match.path}
      exact
    >
      <NewsList />
    </Route>
    <Route
      path={`${match.path}/:topicId`}
    >
      <NewsFullContent />
    </Route>
  </Switch>
</Router>
    );

这是NewsFullContent(呈现新闻的文件)的代码:

import React, { useEffect } from 'react';
import styled from 'styled-components';
import BackButton from '../../../components/BackButton';
import { withRouter, useParams } from 'react-router-dom';
import apis from '../../../app/apis';
import cts from '../../../app/cts';

const NewsTitle = styled.h1`
  font-size: 14pt;
`;

const NewsDate = styled.h3`
  font-size: 10pt;
  color: #aaa;
`;

const NewsContent = styled.div`

`;

const NewsType = styled.h4`
  font-size: 8pt;
  color: #ddd;
`;

const NewsFullContent = ({ location }) => {
  
  const {
    title, content, type, date
  } = location.state;

  return (
    <div>
      <BackButton />
      <NewsTitle>{title}</NewsTitle>
      <NewsDate>{date}</NewsDate>
      <NewsContent
        dangerouslySetInnerHTML={{ __html: content }}
      >
      </NewsContent>
      <NewsType>type: {type}</NewsType>
    </div>
  );
};

export default withRouter(NewsFullContent);

结果如下:

【问题讨论】:

标签: reactjs react-router nested-routes


【解决方案1】:

BackButton 组件中你可以使用useHistory

import {useHistory} from "react-router-dom";
const BackButton = (props) => 
{
 const history = useHistory()
 const onClick = (e) => {
  history.pop() 
  //or
  history.push('/') //if you wan't to go to the homepage
 }
 return <Button onClick={onClick}/>
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2019-01-27
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多