react父组件更改props子组件无法刷新原因及解决方法
作者:奉先何在2019
使用过vue的朋友都知道,vue父组件更改props的值,子组件是会刷新的,而react就未必,今天通过一个例子给大家介绍react父组件更改props子组件无法刷新原因,需要的朋友可以参考下
项目场景:
使用过vue的朋友都知道,vue父组件更改props的值,子组件是会刷新的,而react就未必。
先看以下例子:
1、创建父组件
antd-mobile依赖需要自行引入
export default class Parent2 extends Component {
constructor(props){
super(props)
//初始化state
this.state={
parentVal: 10,
count=1
handleClick=()=>{
this.setState({
parentVal:this.state.parentVal+1
changeCount=()=>{
this.count=this.count+1
console.log(this.count)
componentDidMount() {
console.log("父组件生命周期======:Mount")
//挂载完成后更新状态值,render()结束后会执行componentDidUpdate()钩子函数
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("父组件生命周期======:Update")
componentWillUnmount() {
console.log("父组件生命周期======:Unmount")
render() {
console.log("父组件生命周期======:render")
return (
<p>{this.state.parentVal}</p>
<Divider>分割线</Divider>
<Button color='primary' size='small' onClick={this.handleClick}>更改state的值</Button>
<p>父组件调用setState()时,子组件也会执行render()方法,</p>
<Button color='primary' size='small' onClick={this.changeCount}>更改count的值</Button>
<Child2 number={this.state.parentVal} count={this.count}/>
2、创建子组件