gpt4 book ai didi

javascript - 子组件不使用 React Router v4 渲染

转载 作者:行者123 更新时间:2023-11-30 06:21:13 25 4
gpt4 key购买 nike

我正在尝试 React 嵌套路由,这就是我的应用程序的样子

Posts.js(父(复数)组件)渲染良好。

import React from "react";
import { Route } from "react-router-dom";


import Post from "./Post";
import { Link, Switch } from "react-router-dom";


const Posts = ({ match }) => {
return (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>Rendering with React</Link>
</li>
<li>
<Link to={`${match.url}/components`}>Components</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>Props v. State</Link>
</li>
</ul>

<div>

<Route path={`${match.path}/:topicId`} component={Post} />
<Route
exact
path={match.path}
render={() => <h3>Please select a topic.</h3>}
/>
</div>

</div>
)}

export default Posts;

Post 组件(子(单数)组件)

import React from "react";

const Post = ({ match }) => (
<div>
<h1>Child component</h1>
<h3>{match.params.topicId}</h3>
</div>
);
export default Post;

不确定这里缺少什么配置,父组件在路由上渲染正常,而子组件内容未渲染

控制台没有错误。


父路由配置

import React from "react";
import { Switch, Route,NavLink } from "react-router-dom";

import Home from "./container/home/Home";
import About from "./container/about/About";
import Posts from "./container/post/posts";
import PageNotFound from "./container/Error/404";

const routes = () => (
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route exact path="/post" component={Posts}></Route>
<Route component={PageNotFound}> </Route>*/}
</Switch>

)


export default routes;

App.js

import React, { Component } from 'react';
import './App.css';
import Layout from "./hoc/layout/layout";



class App extends Component {
render() {
return (
<Layout></Layout>
);
}}

export default App;

最佳答案

所以你的代码中的错误是非常微不足道的。在父路由中,即呈现 Posts 组件的路由,你有一个 exact 关键字,因此 Routes/posts/:postId 不会将这个确切的路由与路径 /post 匹配,因此内部路由或嵌套的子路由将不起作用

你需要改变你的路由配置

const routes = () => (
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/about" component={About}></Route>
<Route path="/post" component={Posts}></Route>
<Route component={PageNotFound}> </Route>*/}
</Switch>
)

export default routes;

关于javascript - 子组件不使用 React Router v4 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52945842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com