Реагировать на роутер - правильно используя ссылки внутри вложенных маршрутов
Я пытаюсь получить фид блога, который, когда пользователь нажимает на любой пост в блоге, изменяет маршрут, отображая только отдельный пост + заголовок. При этом используются несколько вложенных маршрутов с реакции-маршрутизатором, и во всех руководствах показано, как отображать динамические данные дальше в гнезде, а не как переопределить родительский маршрут.
Компонент блога:
class Blog extends React.Component {
constructor(props) {
super(props);
}
render() {
const posts = [
{ id: 1, title: "Post 1", slug: "post-1" },
{ id: 2, title: "Post 2", slug: "post-2" },
{ id: 3, title: "Post 3", slug: "post-3" }
];
return (
<>
<Header />
<Route
exact
path="/"
render={() => (
<>
<SidebarLeft />
<Feed />
<SidebarRight />
</>
)}
/>
{/* I need to somehow pass the postTitle & postSlug props by only having access to the slug url param */}
<Route path="/articles/:postSlug" component={Post} />
</>
);
}
}
Кормовой компонент:
class Feed extends React.Component {
constructor(props) {
super(props);
}
render() {
// gets posts from props
var jsonPosts = this.props.posts;
var arr = [];
Object.keys(jsonPosts).forEach(function(key) {
arr.push(jsonPosts[key]);
});
return (
<>
{arr.map(post => (
<Post
key={post.id}
postSlug={post.slug}
postTitle={post.title}
/>
))}
</>
);
}
}
Почтовый компонент:
class Post extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>{this.props.postTitle}</h1>
<Link to={'/articles/' + this.props.postSlug}>{this.props.postSlug}</Link>
);
}
}
index.jsx
// renders all of react
ReactDOM.render(
<Router>
<Route path="/" component={Blog} />
</Router>,
document.getElementById('root')
);
У меня есть проблема Feed
работает просто отлично, и все Post
ссылки работают. Это как только я нажимаю на любой из сообщений, реагировать не знает, какие Post
Я пытаюсь получить доступ.
Здесь я не уверен, как поступить, так как все учебники, которые я нашел, просто показывают Post
Компонент вложен дальше вниз. Как мне сказать, реагировать на сообщение, которое я пытаюсь просмотреть, и сделать так, чтобы он отображал соответствующий маршрут в Blog
составная часть?
1 ответ
Ваш код работает нормально, но вы должны добавить дополнительную логику, чтобы передать правильные реквизиты, когда /articles/:postSlug
матч.
пример
class Blog extends React.Component {
render() {
const posts = [
{ id: 1, title: "Post 1", slug: "post-1" },
{ id: 2, title: "Post 2", slug: "post-2" },
{ id: 3, title: "Post 3", slug: "post-3" }
];
return (
<>
<Header />
<Switch>
<Route
exact
path="/"
render={() => (
<Feed posts={posts} />
)}
/>
<Route
path="/articles/:postSlug"
render={props => {
const post = posts.find(p => p.slug === props.match.params.postSlug);
if (!post) {
return null;
}
return <Post {...props} postTitle={post.title} postSlug={post.slug} />;
}}
/>
</Switch>
</>
);
}
}