2017-03-23 42 views
1

当我使用react-router更改路由时,componentDidUpdate是否会触发?我修改了示例代码,似乎无法使其工作。React Router 4 componentDidUpdate not firing

我做了家庭组件日志一些文本,但它似乎没有解雇。任何帮助表示赞赏,谢谢!

代码:

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import App from './App'; 
import './index.css'; 
import { 
    BrowserRouter as Router, 
    Route, 
    Link 
} from 'react-router-dom' 

const BasicExample =() => (
    <Router> 
     <div> 
      <ul> 
       <li><Link to="/">Home</Link></li> 
       <li><Link to="/about">About</Link></li> 
       <li><Link to="/topics">Topics</Link></li> 
      </ul> 

      <hr/> 

      <Route exact path="/" component={Home}/> 
      <Route path="/about" component={About}/> 
      <Route path="/topics" component={Topics}/> 
     </div> 
    </Router> 
) 

class Home extends React.Component { 
    render() { 
     return (<div> 
      <h2>Home</h2> 
     </div>); 
    } 

    componentDidUpdate() { 
     console.log("Updated!"); 
    } 
} 


const About =() => (
    <div> 
     <h2>About</h2> 
    </div> 
) 

const Topics = ({ match }) => (
    <div> 
     <h2>Topics</h2> 
     <ul> 
      <li> 
       <Link to={`${match.url}/rendering`}> 
        Rendering with React 
       </Link> 
      </li> 
      <li> 
       <Link to={`${match.url}/components`}> 
        Components 
       </Link> 
      </li> 
      <li> 
       <Link to={`${match.url}/props-v-state`}> 
        Props v. State 
       </Link> 
      </li> 
     </ul> 

     <Route path={`${match.url}/:topicId`} component={Topic}/> 
     <Route exact path={match.url} render={() => (
      <h3>Please select a topic.</h3> 
     )}/> 
    </div> 
) 

const Topic = ({ match }) => (
    <div> 
     <h3>{match.params.topicId}</h3> 
    </div> 
) 

ReactDOM.render(
    <BasicExample />, 
    document.getElementById('root') 
); 

回答

0

作为每DOC

的更新可以通过改变道具或状态引起的。这些方法 被称为当组件被重新呈现:

componentWillReceiveProps()

shouldComponentUpdate()

componentWillUpdate()

渲染()

componentDidUpdate()

componentWillUpdate

componentWillUpdate()被正在接收新 道具或状态时呈现之前立即被调用。在更新发生之前使用此作为 执行准备的机会。对于初始渲染,此方法不称为 。

在首页部分你没有定义任何state并没有使用任何props也that't为什么function将不会被调用。

检查,当你点击点击我的文本这个例子componentWillUpdate将调用:

class Home extends React.Component { 
 
    
 
    constructor(){ 
 
     super(); 
 
     this.state = {a: false} 
 
    } 
 

 
    componentDidUpdate() { 
 
     console.log("Updated!"); 
 
    } 
 
    
 
    render() { 
 
     return (
 
      <div> 
 
       <h2>Home</h2> 
 
       <p onClick={()=>this.setState({a: !this.state.a})}>Click Me</p> 
 
      </div> 
 
     ); 
 
    } 
 
} 
 

 

 
ReactDOM.render(<Home/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'/>