zoukankan      html  css  js  c++  java
  • react-router 同一路由,参数不同,页面没有刷新

    使用 componentWillReceiveProps(newProps) 函数,当 props 改变时,我们就可以在该函数中通过 newProps.match.params.id 拿到新的url参数,进而进行更新。如下

    componentWillReceiveProps(newProps) {
      const id = newProps.match.params.id;
      // 一些操作
    }
    

    如果使用这种方法的话,需要注意的一点是:

    我们可能在react中使用的的组件不止一个,需要执行 componentWillReceiveProps 方法的组件可能是作为子组件存在的。也就是说react-router直接作用的组件是使用 componentWillReceiveProps 组件的父组件
    这个时候路由参数的改变是监测不到的,为了能够监测到,需要在父组件中把 props 传给子组件,就像这样

    <Route path="/hello/:id" component={MyHome} />
     
    export default class MyHome extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
        };
      }
     
      render() {
        return (
          // react-router当url参数改变时不能自动更新页面,为了url参数改变时能够自动更新
          // 在子组件中使用componentWillReceiveProps(),当props改变时会自动调用该函数
          // 但是现在url的参数是直接作用在page(当前页面组件)上的,为了让子组件监测到props
          // 的变化,将props全部传给子组件
           <UserInfo {...this.props} />
        );
      }
    }
    
    export default class UserInfo extends React.Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
     
      componentWillReceiveProps(newProps) {
        const id = newProps.match.params.id;
        //一些操作
      }
     
      render() {
        return (
          <div className="userinfo-container">
          </div>
        );
      }
    }

    .

  • 相关阅读:
    Zabbix的SNMPTrap监控配置
    Delphi 7下最小化到系统托盘
    解决来QQ消息后歌曲音量降低问题
    转载——用Mixer API函数调节控制面板的音频设置
    git branch -D 大写的D 删除分支
    gitlab+TortoiseGit中使用SSH
    SQL 高级查询
    正则表达式校验文件路径
    显示所选择文件的路径地址
    Type InvokeMember()用法简介
  • 原文地址:https://www.cnblogs.com/crazycode2/p/12180560.html
Copyright © 2011-2022 走看看