Javascript 使用不同的url参数在ReactJS路由中共享同一组件而不更新内容
我是ReactJS的新手,我不确定我是否只是做错了(我肯定在一定程度上是这样!),或者我只是需要改变一些东西 所以基本上我从Drupal web服务中引入了一些JSON。我的内容页基本上是相同的页面,一个标题和一些段落文本。所以我认为处理这个问题的最好方法是让一个组件获取并显示页面,该页面通过输入url的ID进行更改 我使用的是React Router Dom(v4),当我重新加载页面时,它会获得具有正确ID的正确页面,但如果我单击导航菜单,它将只显示您单击的第一个页面,但会在地址栏中更新路由 我正在使用Fetch API,调用是在componentDidMount中进行的,我在Google上搜索了很多,似乎我需要使用componentWillReceiveProps做一些事情,因为componentDidMount正在做它应该做的事情,并且只在组件第一次装入页面时更新。但我不知道如何正确使用componentWillReceiveProps。如果我在两个组件WillReceiveProps和componentDidMount中都使用相同的函数,我会让它工作(但不是真的),但这对我来说似乎是错误的。。。这是我的组件:Javascript 使用不同的url参数在ReactJS路由中共享同一组件而不更新内容,javascript,reactjs,react-router,react-router-dom,Javascript,Reactjs,React Router,React Router Dom,我是ReactJS的新手,我不确定我是否只是做错了(我肯定在一定程度上是这样!),或者我只是需要改变一些东西 所以基本上我从Drupal web服务中引入了一些JSON。我的内容页基本上是相同的页面,一个标题和一些段落文本。所以我认为处理这个问题的最好方法是让一个组件获取并显示页面,该页面通过输入url的ID进行更改 我使用的是React Router Dom(v4),当我重新加载页面时,它会获得具有正确ID的正确页面,但如果我单击导航菜单,它将只显示您单击的第一个页面,但会在地址栏中更新路由
import React from 'react';
var urlForSimplePage = id =>
`page-url/${id}`
class SimplePage extends React.Component {
constructor(props) {
super(props)
this.state = {
requestFailed: false,
open: true,
}
}
fetchSimplePage() {
fetch(urlForSimplePage(this.props.match.params.id))
.then(response => {
if (!response.ok) {
throw Error("Network request failed")
}
return response
})
.then(d => d.json())
.then(d => {
this.setState({
SimplePageData: d
})
}, () => {
this.setState({
requestFailed: true
})
})
}
componentDidMount() {
this.fetchSimplePage();
}
componentWillReceiveProps(nextProps) {
this.fetchSimplePage();
}
render() {
if (this.state.requestFailed) return <p>Failed!</p>
if (!this.state.SimplePageData) return <p>Loading...</p>
return (
<div>
<h1>
{this.state.SimplePageData[0].title[0].value}
</h1>
<div dangerouslySetInnerHTML={ {__html: this.state.SimplePageData[0].body[0].value} } />
</div>
)
}
}
export default SimplePage;
从“React”导入React;
var urlForSimplePage=id=>
`页面url/${id}`
类SimplePage扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
请求失败:false,
开放:是的,
}
}
fetchSimplePage(){
获取(urlForSimplePage(this.props.match.params.id))
。然后(响应=>{
如果(!response.ok){
抛出错误(“网络请求失败”)
}
返回响应
})
.then(d=>d.json())
.然后(d=>{
这是我的国家({
SimplePageData:d
})
}, () => {
这是我的国家({
请求失败:true
})
})
}
componentDidMount(){
this.fetchSimplePage();
}
组件将接收道具(下一步){
this.fetchSimplePage();
}
render(){
if(this.state.requestFailed)返回失败
如果(!this.state.SimplePageData)返回正在加载
返回(
{this.state.SimplePageData[0].title[0].value}
)
}
}
导出默认的SimplePage;
您的
在它自己的组件中,我将路由使用的所有组件导入其中,即此页面与路由一起导入页面。如果您尝试使用组件更新生命周期,请检查以前的id是否与当前id不相等,如果不相等,调用fetchSimplePage方法。您的
在哪里?在它自己的组件中,我将路由使用的所有组件导入到该组件中,也就是说,此页面将与路由一起导入页面。如果您尝试使用componentDidUpdate生命周期,请检查以前的id是否与当前id不相等,如果不相等,请调用fetchSimplePage方法。