javascript - setState方法导致 "Warning: setState(...): Can only update a mounted or mounting component.."错误

标签 javascript reactjs react-native

在下面的代码中,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.

最佳答案

有两种方法可以做到这一点。如果您想在安装组件之前渲染跨度,请摆脱 setState 并在构造函数中执行此操作:

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

如果您希望先安装组件 - 则从构造函数中删除 setState 并将其移至 componentDidMount() 中:

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

关于javascript - setState方法导致 "Warning: setState(...): Can only update a mounted or mounting component.."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41452917/

相关文章:

javascript - 地铁 bundler : Cannot read properties of undefined (reading 'transformFile' )

android - React Native Maps - 标记从一个坐标到另一个坐标的平滑移动

javascript - 是否可以使用 .print() 函数从特定选择器打印内容?

javascript - index.js for npm package for browser transpiled with babel

javascript - 如何保证传递的对象键可以使用 Typescript 进行调用?

reactjs - 当搜索字符串不在选项标签中时,有没有办法使用 MUI 自动完成?

javascript - 使用 Istanbul + Webpack 对 JSX 文件进行代码覆盖

javascript - 我想使用 Javascript 使 3 个或更多 div 依次显示

javascript - 访问使用 Object.create 创建的 JavaScript 属性的 get/set 方法

react-native - 终极版/传奇 : How to fire an action (put) inside a callback without channels (use sagas as normal generator functions)