严格模式对React的运行时行为提供了以下限制:
- 不能在组件中使用不安全的生命周期方法,如componentWillMount、componentWillReceiveProps和componentWillUpdate。
- 不能在组件中使用ref属性。
- 不能在组件中使用key属性。
- 不能在组件中使用findDOMNode方法。
- 不能在组件中使用setState方法的第二个参数。
- 不能在组件中使用forceUpdate方法。
- 不能在组件中使用createClass方法。
- 不能在组件中使用getInitialState方法。
- 不能在组件中使用getDefaultProps方法。
- 不能在组件中使用propTypes属性。
- 不能在组件中使用defaultProps属性。
- 不能在组件中使用shouldComponentUpdate方法。
我们先看一个例子:
import React,{PureComponent,StrictMode} from "react";
import { findDOMNode } from "react-dom"
import Home from "./pages/Home";
import Profile from "./pages/Profile"
export class App extends PureComponent {
render(){
return (
<div>
<StrictMode>
<Home></Home>
</StrictMode>
<Profile></Profile>
</div>
)
}
}
export default App;在上面的例子中,我们使用了StrictMode,它有下面几个特点:
- 检测组件中的错误。如果组件中存在错误,React会打印出警告信息。
- 检测组件中的不安全的生命周期方法。如果组件中使用了不安全的生命周期方法,React会打印出警告信息。
- 严格模式不会影响组件的正常运行。
- 严格模式不会影响组件的性能。
然后我们看一下Home组件是如何写的:
import React,{PureComponent} from "react";
export class Home extends PureComponent {
// UNSAFE_componentWillMount(){
// console.log("Home UNSAFE_componentWillMount")
// }
constructor(props){
super(props)
console.log("Home Constructor")
}
componentDidCatch(){
console.log("Home componentDidMount")
}
render(){
console.log("Home Render")
return (
<div>
{/* <h2 ref="title">Home Title</h2> */}
<h2>Home</h2>
</div>
)
}
}
export default Home;在上面的例子中,我们使用了componentDidCatch方法,这个方法会在组件发生错误时被调用。但是,我们没有使用UNSAFE_componentWillMount方法,因为这个方法是React 16.3版本中引入的。
Profile组件
我们再看一下Profile组件是如何写的:
import React,{PureComponent} from "react";
export class Profile extends PureComponent {
UNSAFE_componentWillMount(){
console.log("UNSAFE_componentWillMount")
}
componentDidMount(){
// console.log(this.refs.title)
console.log("Profile componentDidMount")
}
render(){
console.log("Profile render")
return (
<div>
<h2 ref="title" >Profile Title</h2>
</div>
)
}
}
export default Profile在上面的代码中,我们使用了UNSAFE_componentWillMount方法,这个方法会在组件挂载之前被调用。
运行结果
我们运行一下上面的代码,看看会出现什么结果。

运行结果控制台输出中有一条报错信息,是由于我们使用ref属性不规范导致的,不过不影响程序的正常运行。
感谢阅读
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。