【发布时间】: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.
【问题讨论】:
-
这是因为你在构造函数中设置状态。尝试将其移至
componentDidMount
标签: javascript reactjs react-native