【问题标题】:TypeError: Cannot assign to read only property 'statusKnown' of object '#<Object>'TypeError:无法分配给对象“#<Object>”的只读属性“statusKnown”
【发布时间】:2020-04-09 21:15:27
【问题描述】:

我正在尝试根据我的基于 react 类的组件中的 props 更新状态,但出现错误

TypeError:无法分配给对象的只读属性“statusKnown” '#'

下面是代码

componentDidMount(){
    this.calClass()
  }

calClass = () => {
    console.log(this.props.statusKnown, this.state.active);
    if (this.props.statusKnown == "deactive") this.setState({ active: false });
    else if ((this.props.statusKnown = "active")) this.setState({ active: true });
  };

然后在父组件中

<Button item={item} categoryID={categoryID} statusKnown={status}/>;

如果 react 不允许这件事,那么可能的解决方案是什么?

【问题讨论】:

  • 如果这是问题,你能接受我的回答吗?

标签: javascript reactjs


【解决方案1】:

您错过了一些= 标志。您应该始终使用===

componentDidMount(){
    this.calClass()
}

calClass = () => {
    console.log(this.props.statusKnown, this.state.active);
    if (this.props.statusKnown === "deactive") this.setState({ active: false });
    else if ((this.props.statusKnown === "active")) this.setState({ active: true });
};

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 2021-09-26
    • 1970-01-01
    • 2019-02-08
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多