严格模式对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属性不规范导致的,不过不影响程序的正常运行。
感谢阅读
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我