gpt4 book ai didi

javascript - 与阵列的一部分相比, react 路由器 slug

转载 作者:行者123 更新时间:2023-12-03 07:13:58 25 4
gpt4 key购买 nike

我开始尝试 React 路由器和动态匹配。我想创建一个函数,将 URL 的 slug 与 JSON 文件中的 slug 匹配。 我得到的错误:类型错误:无法获取未定义或空引用的属性“slug”

我认为 url 的“Slug”未定义,但我不确定如何修复它。

screenshot of error

我的 routes.js 代码:

import React from 'react';
import Header from './components/header/header.js';
import Home from './components/home/home.js';
import About from './components/about/about.js';
import NotFound from './components/notFound/notFound.js'
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import PostPage from './components/postpage/postpage.js'
import posts from './files/data.json';

class Routes extends React.Component {
render(){
return (
<Router>
<div>
<Header />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
<Route path="/:slug" component={props => {
const postt = posts.posts.filter (post => props.params.slug === post.slug)
console.log(postt.length)
return <PostPage post={postt} />
} } />
}}/>
<Route component={NotFound} />
</Switch>

</div>
</Router>
);
}
}

export default Routes;

PostsPage.js:

import React from 'react';

import Post from '../post/post.js'

const PostPage = (props) => (
<div>
<Post {...props.post}/>
</div>
);
export default PostPage;

和 posts.js:

import React from 'react'; 
import { Link } from 'react-router-dom';
import './post.css';

class Post extends React.Component {
render(){
return(
<div>
<div >
<h2 className='subTitle'><Link to={`/post/${this.props.slug}`} className='link'>{this.props.title}</Link></h2>
<p className='content'>{this.props.excerpt}</p>

</div>
</div>
);
}
}

export default Post;

如果你做到了这一点,谢谢你的帮助

最佳答案

slug 变量在您丢失的匹配 Prop 中给出。

<Route path="/:slug" render={props => {
const postt = posts.posts.filter (post => props.match.params.slug === post.slug)
console.log(postt.length)
return <PostPage post={postt} />
} } />
}}/>

此外,不要内联组件,而是使用渲染函数。来自文档:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component prop, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

https://reacttraining.com/react-router/web/api/Route/render-func

关于javascript - 与阵列的一部分相比, react 路由器 slug,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48973588/

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