【问题标题】:Updating parent component without a call back function in react js在反应js中更新没有回调函数的父组件
【发布时间】:2020-05-16 12:50:45
【问题描述】:

我正在使用具有子组件的组件对 React js 进行 POC 编码。据我所知,除了通过从子组件到子组件的回调函数之外,没有其他方法可以从子组件更新父组件的状态父组件。就我而言,我尝试将父级的状态传递给子级并将它们直接设置为子级作为道具(this.props.)。我注意到如果我更改子级的状态,则父级的状态也在更新。我有点困惑。有人可以帮忙吗? 这是我的代码。

index.js

ReactDOM.render(<App2/>,document.getElementById('root'));

App2.js - 父组件

import React from 'react'
import ScreenTest From './ScreenTest'

class App2 extends React.Component{

 state={
   address : {
         houseName:'1234 House Name'
   }
}

render(){
 return(
    <ScreenTest parentState={this.state} address={this.state.address} /> 
  )
}

}

ScreenTest.jsx - 子组件

import React from 'react';

class ScreenTest extends React.Component{
 state={
    parentState: this.props.parentState,
    address : this.props.address
}

clickButton = () =>{
  let addressTemp = this.state.address;
  addressTemp.city= "Kerala";
  this.setState({
   address:addressTemp
  })
}

render(){
  console.log("To view the state when the screen renders",this.state)
  return(
       <a onClick={this.clickButton}>Click me to update the state and re render </a>
  )
}

}

代码说明: 我正在调用具有子组件 ScreenTest 的 App2 组件。我将 App2 的 currentState 传递给 ScreenTest。在 ScreenTest 中,我根据作为道具传递的值设置状态。在 ScreenTest 中,单击时我有一个锚标记,更新 ScreenTest 的“地址”状态并重新渲染屏幕。当屏幕重新渲染时,我检查状态以查看 parentState 也使用新地址更新(即添加了城市)。

请告诉我 parentState 是如何受到它的影响的。我有点糊涂了。

【问题讨论】:

    标签: reactjs react-props react-component


    【解决方案1】:

    您必须注意,当文档说要从子级更新父级状态时,您必须使用回调并让父级更新其状态,这是理想和正确的做法

    在您的代码中,您意外地更新了父状态,您通过调用改变了状态

      let addressTemp = this.state.address;
      addressTemp.city= "Kerala";
    

    在 Javascript 中,对象是通过引用使用的,直接更新对象中的属性将为使用该引用的任何人更新它

    因此,当您在构造函数中将道具分配给状态时,如下所示

    state={
        parentState: this.props.parentState,
        address : this.props.address
    }
    

    state 属性保存 props 对象的引用,因此当您通过更新 addressTemp 状态来改变 state 属性时,props 也会更新

    更新状态的理想方法是克隆它然后进行更改以避免意外问题

    clickButton = () =>{
      let addressTemp = {...this.state.address}; // clone state
      addressTemp.city= "Kerala";
      this.setState({
       address:addressTemp
      })
    }
    

    【讨论】:

    • 感谢您的回答。需要两个澄清 1)您是否看到使用我的方法可能存在的问题,即在子节点中传递状态并对其进行变异 2)这是否会给 DOM 增加任何性能开销(即重新渲染 DOM)?
    • @MukeshKeshu 反应告诉你不要改变状态/道具是有原因的。 1) React 状态更新和生命周期依赖于很多状态的引用。 2)调试变得非常困难
    猜你喜欢
    • 2019-08-11
    • 2021-10-31
    • 2021-07-22
    • 2017-04-17
    • 2018-11-23
    • 1970-01-01
    • 2021-02-22
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多