首页 > 解决方案 > 在反应js中更新没有回调函数的父组件

问题描述

我正在使用具有子组件的组件对 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 是如何受到它的影响的。我有点困惑。

标签: reactjsreact-propsreact-component

解决方案


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

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

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

推荐阅读