在 React js 中更新 parent 没有回调函数的组件

Updating parent component without a call back function in react js

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

index.js

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

App2.js - Parent 组件

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 - Child 组件

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>
  )
}

}

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

请告诉我parent州如何也受到它的影响。我有点困惑。

你必须注意,当文档说为了从子更新父状态,你必须使用回调并让父更新它的状态,这是理想和正确的做法

在您的代码中,您不小心更新了您通过调用

改变状态的父状态
  let addressTemp = this.state.address;
  addressTemp.city= "Kerala";

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

所以当你像下面这样在构造函数中将 props 分配给 state 时

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

状态属性保存 props 对象的引用,因此当您通过更新 addressTemp state

来改变状态 属性 时,props 也会更新

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

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