【发布时间】:2019-04-02 20:53:36
【问题描述】:
我有一个 React 组件,它在另一个组件中使用 Array.prototype.map() 多次呈现。
第一个组件的构造函数应该被调用多少次?我期望映射数组的长度是映射数组的长度,但它似乎只被调用一次。
在我的具体代码中,它是在最后一个 render() 之前调用的。
示例代码:
class ComponentB extends Component {
constructor(props) {
super(props) // added upon first reply
this.handleObjectAdd = this.handleObject.bind(this);
this.state.objects = [];
}
handleObjectAdd() {
this.state.objects.unshift({prop1: this.state.objects.length + 1});
}
render() {
return (
<div>
<button onClick={this.handleObjectAdd}>ADD</button>
{ this.state.objects.map((object, index) =>
<ComponentA key={index} details={object}/>
)
}
</div>
)
})
}
}
class ComponentA extends Component {
constructor(props) {
super(props) // added upon first reply
console.log('ComponentA constructor called');
}
render() {
console.log('ComponentA render() called');
return (
<input type="text" value={this.props.details.prop1}></input>
)
}
}
对于一个包含 5 个元素的数组(所有 ComponentA 实例),我得到以下几行:
ComponentA render() called
ComponentA render() called
ComponentA render() called
ComponentA render() called
ComponentA constructor called
ComponentA render() called
此外,构造函数的日志行总是出现在最后一个构造函数日志行之前,与数组元素的数量无关。
为什么会出现上面这样的日志输出?希望有任何见解。
这被标记为与React Rerender dynamic Components (Solr) 重复,但事实并非如此。
【问题讨论】:
标签: reactjs constructor components render array.prototype.map