React-router-dom - 链接更改 url 但不呈现 [英] React-router-dom - Link change url but does not render

查看:23
本文介绍了React-router-dom - 链接更改 url 但不呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手,我制作了一个 以从 dy 数据转到下一个或上一个项目(例如,如果我在 user/2 视图上,则上一个链接转到用户/1,下一个链接转到用户/3),网址已正确更改,但根本不呈现组件并且根本不重新加载数据.

我读到这是因为组件没有检测到子组件没有改变状态,所以父组件没有呈现.

我尝试使用 withRouter 但我遇到了一个错误:你不应该使用 <Route>或 withRouter() 在 <Router> 之外,如果有人有解决方案和一些解释,我不明白我在做什么,我将不胜感激:)

App.js:

import React, { Component } from 'react';进口 {路线,转变,带路由器,来自'反应路由器-dom';从./pages/home"导入主页;从 './pages/single' 导入 SinglePage;类 App 扩展组件 {使成为() {返回 (<开关><div><路由精确路径="/" component={HomePage}/><Route path="/:id" component={SinglePage}/>

</开关>);}}导出默认 withRouter(App);

Single.js :

import React, { Component } from 'react';从../components/details"导入详细信息从'../components/header'导入标题从反应物化"导入 { ProgressBar };类 SinglePage 扩展组件 {构造函数(道具){超级(道具);this.state = {数据:{数据:空},}}componentDidMount() {获取(`http://localhost:1337/${this.props.match.params.id}`).then((res) => res.json()).then((json) => {this.setState({数据:json,});});}使成为() {const { 数据 } = this.state;返回 (<div><h2>单页{!数据 ?(<进度条/>) : (<div><Header id={this.props.match.params.id}/><详细信息项={数据}/>

)}

);}}导出默认单页;

Header.js:

import React, { Component } from 'react';从 'prop-types' 导入 PropTypes;从'react-router-dom'导入{链接,withRouter};类头扩展组件{静态 propTypes = {项目:PropTypes.shape({数据:PropTypes.string.isRequired,}).是必须的,}使成为() {const prev = parseInt(this.props.id) - 1const next = parseInt(this.props.id) + 1返回 (<div><链接到="/">返回</Link><链接到={`/${prev}`}>先例 </Link><链接到={`/${next}`}>Suivant </Link>

)}}导出默认标题;

解决方案

解决方案非常简单.您需要做的就是使用 componentWillReceiveProps 并检查参数是否更新,是否再次获取数据

componentDidMount() {this.getData(this.props.match.params.id);}componentWillReceiveProps(nextProps) {if(this.props.match.params.id !== nextProps.match.params.id) {this.getData(nextProps.match.params.id);}}getData = (param) =>{获取(`http://localhost:1337/${params}`).then((res) => res.json()).then((json) => {this.setState({数据:json,});});}

I'm new to React and I've made a <Link>to go to next or previous item from dy datas(for example, if i am on user/2 view, previous link go to user/1 and next link go to user/3), the url is correctly changed but the component is not rendered at all and the datas are not reloaded at all.

I've read that it's due to the component not detecting that the children is not changing state so the parent component does not render.

I've tried to use withRouter but I've got a error : You should not use <Route> or withRouter() outside a <Router> and I'm not understanding what I'm doing so if someone has the solution and some explanation to it I would be grateful :)

App.js :

import React, { Component } from 'react';
import {
  Route,
  Switch,
  withRouter,
} from 'react-router-dom';


import HomePage from './pages/home';
import SinglePage from './pages/single';

class App extends Component {



  render() {


    return (
      <Switch>
        <div>
          <Route exact path="/" component={HomePage} />
          <Route path="/:id" component={SinglePage} />
        </div>
      </Switch>
    );
  }
}

export default withRouter(App);

Single.js :

import React, { Component } from 'react';
import Details from '../components/details'
import Header from '../components/header'
import { ProgressBar } from 'react-materialize';

class SinglePage extends Component {

  constructor(props) {
    super(props);

    this.state = {
      data: { data: null },
    }
  }

    componentDidMount() {
        fetch(`http://localhost:1337/${this.props.match.params.id}`)
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          data: json,
        });
      });
    }

  render() {

    const { data } = this.state;

    return (

      <div>

        <h2> SinglePage </h2>

        {!data ? (
          <ProgressBar />
        ) : (
          <div>
            <Header id={this.props.match.params.id} />
            <Details item={data} />
          </div>
        )}
      </div>
    );
  }

}

export default SinglePage;

Header.js :

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link, withRouter } from 'react-router-dom';

class Header extends Component {

  static propTypes = {
    item: PropTypes.shape({
      data: PropTypes.string.isRequired,
    }).isRequired,
  }

    render() {
        const prev = parseInt(this.props.id) - 1
        const next = parseInt(this.props.id) + 1

        return (
            <div>
                <Link to="/"> Retour </Link>
                <Link to={`/${prev}`}> Précédent </Link>
                <Link to={`/${next}`}> Suivant </Link>
            </div>
        )
    }
}

export default Header;

解决方案

the solution is pretty-simple. All you need to do is make use of componentWillReceiveProps and check if the param updated, if it did fetch the data again

componentDidMount() {
    this.getData(this.props.match.params.id);  
}

componentWillReceiveProps(nextProps) {
   if(this.props.match.params.id !== nextProps.match.params.id) {
       this.getData(nextProps.match.params.id);
   }
}

getData = (param) => {
   fetch(`http://localhost:1337/${params}`)
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          data: json,
        });
      });
}

这篇关于React-router-dom - 链接更改 url 但不呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆