gpt4 book ai didi

javascript - React Router v4 嵌套路由传递与类组件匹配

转载 作者:行者123 更新时间:2023-11-30 19:56:52 24 4
gpt4 key购买 nike

我正在尝试在我的应用程序中使用嵌套路由。使用类语法声明组件的位置。

如何传递匹配

正如您在下面看到的,我正在使用 componentDidMount() 函数来提取数据,因此我需要拥有成员函数并且我希望该组件能够处理我的所有逻辑。

import React, { Component } from 'react';
import ListItem from './ListItem';
import Post from './Post';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

//holds the state for all the components
//passes into listing
//listing will re-direct to proper post using router

export default class Blog extends Component {

constructor(props){
super(props);

this.state = {
articles: [],
content: null
};
}

storeData = (data) => {
const articles = data.map((post, index) => {
return {
key: index,
title: post.title.rendered,
content: post.content.rendered,
excerpt: post.excerpt.rendered,
slug: post.slug
};
});

this.setState(
{
articles: articles
}
);
};

componentDidMount() {

let articles = [];
fetch('https://XXXXX.com/posts/')
.then(data => data.json())
.then(this.storeData).catch(err => console.log(err));

}

render(){

return(
<div className="blog">
<h2> Listings </h2>
{ this.state.articles.map(post => (
<Link to= { `path/${post.slug}` } >
<ListItem
key={post.key}
title={post.title}
content={post.content}
/>
</Link>
))
}
<Route path='posts/:slug' component={Post} />
</div>

);
}

}

最佳答案

发现了!

如果你在渲染中看下面,它被保存为 this.props!

但是,现在它呈现下面的组件而不是替换到另一个页面。

  render(){
return(
<div className="blog">
<h2> Listings </h2>
{ this.state.articles.map(post => (
<Link to={ `${this.props.match.url}/${post.slug}` } >
<ListItem
key={post.key}
title={post.title}
content={post.content}
/>
</Link>
))
}
<Route path={ `${this.props.match.path}/:slug` } component={Post} />
</div>
);
}

}

关于javascript - React Router v4 嵌套路由传递与类组件匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53892306/

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