我正在尝试从每个路由器上的服务器中获取内容。
Navigation.js
import { Component } from "react";
import { Link } from "react-router-dom";
export class Navigation extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
all_nav: [
{
menu_name: "News 1",
menu_items_id: "31"
},
{
menu_name: "News 2",
menu_items_id: "32"
},
{
menu_name: "News 3",
menu_items_id: "33"
}
]
};
}
render() {
return (
<ul>
{this.state.all_nav.map((name, key) => (
<li key={key}>
<Link to={`news/${name.menu_items_id}`}>{name.menu_name}</Link>
</li>
))}
<hr />
<li>
<Link to="/">Home</Link>
</li>
</ul>
);
}
}
Navigation.js包含用于路由内容的导航列表。
Index.js
import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import { App } from "./App";
import { NewsList } from "./NewsList";
window.React = React;
render(
<BrowserRouter>
<div>
<Route exact path="/" title="App Title" render={props => <App />} />
<Route path="/news/:filter" render={props => <NewsList {...props} />} />
</div>
</BrowserRouter>,
document.getElementById("root")
);
NewsList.js
import { Component } from "react";
import {Navigation} from './Navigation'
export class NewsList extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
post_record: []
};
}
componentDidMount() {
this.setState({ loading: true });
// console.log(this.props.match.params.filter)
Promise.all([
fetch("https://binodgiri.com.np/api/news_listing.php", {
method: "POST",
headers: {
Accept: "application/json"
},
body: JSON.stringify({
param: this.props.match.params.filter
})
})
])
.then(([all_post_api]) => Promise.all([all_post_api.json()]))
.then(([post_data]) =>
this.setState({
loading: false,
post_record: post_data
})
);
}
render() {
return (
<div>
<h1>Hello Content</h1>
{
this.state.post_record.menu_name
}
<hr />
<Navigation />
</div>
);
}
}
NewsList.js
是主要渲染部分,根据:filter id,应从服务器“ https://binodgiri.com.np/api/news_listing.php”中获取内容
我真正想做的是::
如果我首先单击“新闻1”或任何其他新闻。它呈现完美。如果我想导航到新闻2或其他任何事情,
这是沙盒链接: https://codesandbox.io/s/vykxvp17j7
先谢谢您。
答案 0 :(得分:1)
您应该添加此逻辑。
由于componentDidMount
已经安装在第一次链接单击上,因此不会再次调用它,因此您需要添加以下生命周期函数。 (这是快速解决方案,您也可以重新排列逻辑以获得更好的性能。)
componentDidUpdate(prevProps) {
if (this.props.match.params.filter !== prevProps.match.params.filter) {
Promise.all([
fetch("https://binodgiri.com.np/api/news_listing.php", {
method: "POST",
headers: {
Accept: "application/json"
},
body: JSON.stringify({
param: this.props.match.params.filter
})
})
])
.then(([all_post_api]) => Promise.all([all_post_api.json()]))
.then(([post_data]) =>
this.setState({
loading: false,
post_record: post_data
})
);
}
}
在Navigation.js
<Link to={`/news/${name.menu_items_id}`}>{name.menu_name}</Link>