【问题标题】:setState method causes "Warning: setState(...): Can only update a mounted or mounting component.." errorsetState 方法导致“警告:setState(...):只能更新已安装或正在安装的组件..”错误
【发布时间】:2017-05-18 02:24:45
【问题描述】:

在下面的代码中cityNameLength是一个数字,代表一个城市名称的长度。 我的目标是根据cityNameLength 值渲染多个元素。 因此,如果 cityNameLength 等于 5,我希望有 5 个 span 元素。

这就是我所拥有的:

class myCitiesClass extends Component {
  constructor(props) {
      super(props);
      this.state = {cLength: 0};
      this.setState({ cLength: this.props.cityNameLength });
  }


  renderDivs() { 
    var products = []

    var cNameLength = this.state.cLength
    for (var p = 0; p < cNameLength; p++){
      products.push( <span className='indent' key={p}>{p}</span> );
    }
    return products
  }

  render() {    
    return (
      <View>
        <Text>City name length: {this.props.cityNameLength}</Text>
        <View>{this.renderDivs()}</View>
      </View>
    );
  }
}

这是我得到的错误:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

您不能在构造函数中使用this.setState。幸运的是,您不需要这样做。可以在赋值中将状态设置为正确的值:

constructor(props) {
      super(props);
      this.state = { cLength: this.props.cityNameLength };
}

但是,这段代码也不好。从道具分配状态不一定是错误,但您必须清楚自己在做什么以及为什么(事情是道具可以随时从顶级组件更改,你会必须与覆盖的componentWillReceiveProps() 保持状态同步才能使您的组件正常工作)。如果你怀疑你这样做,你应该避免它。

在您的情况下,这应该很容易,因为您根本不需要状态。删除构造函数,并使用this.props.cityNameLength 而不是this.state.cLength

当您从 componentDidMount() 修改状态时,您应该非常了解您在做什么(因为您在组件刚刚渲染后立即触发另一个渲染 - 为什么?) .在 99% 的情况下,这是错误的。不过,这并不像在 componentDidUpdate 中那样致命。

【讨论】:

    【解决方案2】:

    有两种方法可以做到这一点。如果你想在安装组件之前渲染 span,去掉 setState 并在构造函数中这样做:

    this.state= {cLength: this.props.cityNameLength };
    

    如果您希望组件先挂载 - 然后从构造函数中移除 setState 并将其移动到 componentDidMount()

    componentDidMount() {
      this.setState({ cLength: this.props.cityNameLength });
    }
    

    【讨论】:

    • 谢谢。关于这段代码,我能再问你一件事吗?
    • 好的,问吧。
    • 我在“for”循环中放了一个 console.log("test") 并打印了 cNameLength 次,但我看不到跨度。这样做是否正确: {this.renderDivs()} ?
    • 是的,如果你使用 React-Native,你不能使用 span,你必须使用 Views。
    猜你喜欢
    • 2017-04-26
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 2019-08-15
    • 1970-01-01
    • 2016-09-25
    • 2018-03-26
    相关资源
    最近更新 更多