React Router v4带有参数的路由未渲染/刷新

4
我有一个针对动态参数的路由。例如,当URL为my-app.com/about时,它将从REST API获取关于页面的JSON数据。我使用一个名为Page的组件来处理所有URL参数。
当我点击导航链接时,URL会更改,但除非我刷新页面,否则不会呈现新内容。
我的代码:
class App extends Component {
  render() {
    return (

        <BrowserRouter>
            <div>

                <NavLink to='/home'>Home</NavLink>
                <NavLink to='/about'>About</NavLink>
                <NavLink to='/contact'>Contact</NavLink>                 

                <Switch>                                                                  
                  <Route path="/:slug" component={ Page } />                                    
                </Switch>

            </div>
          </BrowserRouter>

    );
  }
}

我的页面组件。我正在获取JSON以渲染页面内容:

import React, { Component } from 'react';
import axios from 'axios';

class Page extends Component {

    constructor() {
      super();
      this.state = {
        page: []
      };
    }

  componentDidMount() { 
    axios.get('http://example.com/wp-json/wp/v2/pages?slug=' + this.props.match.params.slug)
    .then(response => {
      this.setState({ page: response.data });
    })
    .catch(error => {
        console.log(error);
    });
  }

  render() {
    return (

      <div>
        <h2>Single Page template</h2>
        {this.state.page.map(single => {
            return(
            <div>
              <h1>{single.title.rendered}</h1>
              <p>{single.content.rendered}</p>
            </div>                                        
            );
        })}
      </div>
    );
  }
}

export default Page;

当我点击不同的链接时,如何在路由器中呈现新数据?而不需要重新加载页面。

1个回答

4

componentDidMount只有在组件挂载时运行,当URL发生更改时,slug变量将会改变,但是组件不会被卸载和重新挂载。

你需要在componentDidUpdate中检查slug参数是否已更改,如果是,则获取数据。

示例

class Page extends Component {
  state = {
    page: []
  };

  componentDidMount() {
    this.getPageData();
  }

  componentDidUpdate(prevProps) {
    if (prevProps.match.params.slug !== this.props.match.params.slug) {
      this.getPageData();
    }
  }

  getPageData = () => {
    axios
      .get(`http://example.com/wp-json/wp/v2/pages?slug=${this.props.match.params.slug}`)
      .then(response => {
        this.setState({ page: response.data });
      })
      .catch(error => {
        console.error(error);
      });
  };

  // ...
}

标记JS在所有React特定问题中的意义是什么,一个精通JS但不熟悉React的极客可以如何帮助呢?顺便说一句,你做得很好,看到那个图表真是太棒了 :) - Mayank Shukla
1
@MayankShukla 谢谢。我认为有相当多的 JavaScript 重叠,并且它还提供了语法高亮。但是你说得对,这并不适用于这个特定的问题。 - Tholle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接