您现在的位置是:网站首页> 编程资料编程资料

react父组件更改props子组件无法刷新原因及解决方法_React_

2023-05-24 291人已围观

简介 react父组件更改props子组件无法刷新原因及解决方法_React_

项目场景:

使用过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 ( 
父组件

{this.state.parentVal}

分割线

父组件调用setState()时,子组件也会执行render()方法,

) } }

2、创建子组件

export default class Child2 extends Component { constructor(props){ super(props) } componentDidMount() { console.log("子组件生命周期======:Mount") } //挂载完成后更新状态值,render()结束后会执行componentDidUpdate()钩子函数 componentDidUpdate(prevProps, prevState, snapshot) { console.log("子组件生命周期======:Update") } componentWillUnmount() { console.log("子组件生命周期======:Unmount") } render() { console.log("子组件生命周期======:render") return ( 

父组件state中传值:{this.props.number}

父组件非state中传值:{this.props.count}

) } }

问题描述

这里有两个变量,一个count,不是父组件state中的值,一个numer是父组件state中的值。

点击更改‘更改state的值’按钮,父子组件同步刷新,而点击更改count的值按钮,子组件不会刷新

原因分析:

父组件更改count的值,虽然父组件count值改变,但是不会更改子组件的值,props是单向传递的

情况组件挂载生命周期钩子函数执行控制台打印数据

在这里插入图片描述


父组件执行setState()结果:

在这里插入图片描述

  • 要想让子组件更新dom,必须让子组件执行render()方法,而父组件执行render()方法后,子组件也会执行render()方法,这就是为何父组件调用了setSate()方法,子组件会刷新。
  • 当更改了count的值,比如count连续加1,变成了9,此时父组件调用this.setState()更改状态值,

此时子组件的count也变成了9,因为count并没有清除,父子组件又先后调用了render()方法,因此渲染上了最新的props的属性值

如果子组件是函数组件,则render后,count值会变为初始值,那么父组件setState()之后,子组件render()函数执行时收到的还是最初的值,这和子组件是类组件有区别,大家可以自己尝试,

解决方案:

如果想要传递子组件的props改变后刷新子组件dom,就要将父组件的state中的值传给子组件,而不是将普通的变量传递给子组件

vue更改props的值子组件会刷新,因为vue中传递给props的值也是父组件状态中的变量

到此这篇关于react父组件更改props子组件无法刷新原因的文章就介绍到这了,更多相关react父组件更改props子组件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网