使用不同的url参数在ReactJS路由中共享相同的组件而不更新内容

时间:2017-11-03 11:00:21

标签: javascript reactjs react-router react-router-dom

我是ReactJS的新手,我不确定我是否只是做错了(我确定我在某种程度上!)或者我只需要改变一些东西。

所以基本上我从Drupal Web服务中提取了一些JSON。我的内容页面基本上只是同一页面,标题和一些段落文本。所以我认为解决这个问题的最佳方法是让一个组件获取并显示页面,该组件会根据输入到URL中的ID进行更改。

我正在使用React Router Dom(v4),当我重新加载页面时,它会获得具有正确ID的正确页面但是如果我单击导航菜单,它将只显示您单击的第一页,但是更新地址栏中的路线。

我正在使用Fetch API并且在componentDidMount中进行调用,我已经搜索了很多内容,似乎我需要对componentWillReceiveProps做一些事情,因为componentDidMount正在执行它应该做的事情,并且仅在组件第一次时更新安装在页面上。但我无法弄清楚如何正确使用componentWillReceiveProps。如果我在componentWillReceiveProps和componentDidMount中使用相同的函数,我有点工作(但不是真的),但这对我来说似乎不对...这是我的组件:

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;

0 个答案:

没有答案