React父组件接收子组件传递的state为undefined如何解决
问题根源
updateState无对外返回值:你写在setState回调函数里的return仅作用于回调本身,不会作为updateState方法的返回值向外传递,因此调用this.updateState()拿到的默认是undefined- 忽略了
setState的异步特性:setState调用后不会立刻更新组件状态,即使将return写在updateState外层,调用setState后立刻读取this.state.childState拿到的也还是更新前的旧值 - 额外冗余问题:Parent.js中单独引入的
setState没有实际作用,类组件的setState是挂载在实例上的方法,无需单独导入;另外React中DOM节点的类名属性要写className不能写原生的class
修复方案
第一步:修改Child.js逻辑
调整updateState方法,等状态更新完成后主动调用父组件传入的changeState方法传递最新状态,不需要依赖方法返回值传参:
// Child.js 修正后代码 import React, { Component } from 'react' import "./Child.css" export class Child extends Component { constructor(props) { super(props) this.state = { childState: false } this.updateState = this.updateState.bind(this) } updateState(){ this.setState({ childState: !this.state.childState }, () => { // 状态更新完成后调用父组件方法传值 this.props.changeState(this.state.childState) }) } render() { return ( <div className="child"> <h1>{`child state is ${this.state.childState}`}</h1> {/* 直接绑定updateState方法即可 */} <div onClick={this.updateState}>Click</div> </div> ) } } export default Child
第二步:调整Parent.js逻辑(可选,用于同步父组件状态)
如果需要父组件同步子组件的状态,直接用拿到的newState更新父组件状态即可:
// Parent.js 修正后示例 import React, { Component } from 'react' import './Parent.css' import Child from './Child' export class Parent extends Component { constructor(props) { super(props) this.state = { childState: false } } render() { return ( <div className={`parent ${this.state.childState ? 'parent-child-not-clicked' : 'parent-child-clicked'}`}> <h1>{this.state.childState ? 'true' : 'false'}</h1> <Child changeState={(newState) => { console.log(newState) // 同步父组件状态 this.setState({childState: newState}) }}></Child> </div> ) } } export default Parent
内容的提问来源于stack exchange,提问作者joebegborg07
相关产品推荐
相关产品推荐

