gpt4 book ai didi

reactjs - componentDidUpdate 没有触发

转载 作者:行者123 更新时间:2023-12-03 13:13:40 25 4
gpt4 key购买 nike

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

我让主页组件记录了一些文本,但它似乎没有触发。感谢任何帮助,谢谢!

代码:

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')
);

最佳答案

根据 DOC :

An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:

componentWillReceiveProps()

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

componentWillUpdate:

componentWillUpdate() is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.

在 Home 组件中,您没有定义任何 state 并且您也没有使用任何 props,这就是为什么 function 会不被叫。

检查此示例,当您单击“Click Me”文本时,将调用 componentDidUpdate:

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'/>

关于reactjs - componentDidUpdate 没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42971806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com