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