【问题标题】:React: TypeError: this.setState is not a function反应:TypeError:this.setState 不是一个函数
【发布时间】:2021-08-01 11:50:44
【问题描述】:

尝试根据从子级获取的值在父类中设置值时。我收到以下错误:

TypeError: this.setState 不是函数

父类

class Header extends React.Component {
  
    constructor(props) {
    super(props);
    this.state = {
      favoritecolor: "ParentValue RED"
    };
    }

    nameParent(e) {
    this.setState({favoritecolor: e})
    console.log(e); // I am getting the value here from Child. But how to use setState ?
    }
  
    render() {  
    let variableName = ''; 
    return (   
      <div>
        <h1>Value from Child is {this.state.favoritecolor}</h1> 
        <Child nameFn={this.nameParent}/>
      </div>       
      
    );
    }
}

export default Header;

儿童班

export class Child extends React.Component {

    onHClick(e) {
       this.props.nameFn(e); 
    }   

    render() {                
        return (
            <h1 onClick = {this.props.nameFn('Blue Black Green')}>
                Value from parent is = {this.props.name}
            </h1>
        )
     }
}

因此我无法使用 setState 来更新状态。

【问题讨论】:

  • nameParent(e) { 替换为nameParent = (e) =&gt; { 以将this 范围扩大到班级级别。
  • @MaartenDev 这样做我得到 - 错误:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制嵌套更新的数量以防止无限循环
  • 这是因为您直接在Child 中调用nameFn,我提供了一个答案作为解决此问题的方法

标签: javascript jquery reactjs react-redux


【解决方案1】:

有两个错误,第一个与Header组件中的this用法有关。你可以替换

nameParent(e) {

通过

nameParent = (e) => {

this 的范围限定为类级别。

第二个错误是由Child组件引起的,因为它直接调用了提供的函数:

<h1 onClick = {this.props.nameFn('Blue Black Green')}>

应该重构为以下内容来修复错误:

render() {                
    return (
        <h1 onClick = {() => this.props.nameFn('Blue Black Green')}>
            Value from parent is = {this.props.name}
        </h1>
    )
 }

【讨论】:

  • @maartenDev:你用过的'e'有什么用??
  • e 包含 onClick 事件,如果您不需要访问event 数据,可以将其替换为() =&gt; this.props.nameFn('Blue Black Green')
【解决方案2】:

将函数绑定到类的this

<Child nameFn={this.nameParent.bind(this)}/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2020-12-15
    • 2023-04-09
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多