Reputation: 9419
here is my render
method of FormEl
component.
return <div>
<button type="button" onClick={this.clicked}>click to add 1 input</button>
<Inputs count={this.state.childcount}/>
</div>
in clicked
method I update the childcount
by 1 using setState
this is the Inputs
class
class Inputs extends React.Component {
constructor(props) {
super(props);
console.log("Input constructor is running.");
this.state = {value: '', p: "p", count: props.count};
}
render() {
let c = [];
for (let i = 0; i < this.state.count; i++) {
c.push(
<div key={"id-" + (i * 10)}>
<input type="text" defaultValue={this.state.value}/>
<p> {this.state.p}</p>
</div>);
}
return <div>
{c}
</div>;
}
}
But, when I update the childcount
in clicked
, I can see FormEl
is re-rendered, count
in <Inputs..
is increased accordingly. But it does not call constructor
of Inputs
other than first (page loading) time.
Upvotes: 0
Views: 133
Reputation: 2278
constructor is meant to be only called once, so you only might set an initial state there.
In fact as you are not modifying the state from Inputs class, you do not need any state at all. You can declare const value=""; const p="p"; on the top of your render method. And just use this.props.count instead of this.state.count
You can remove the constructor in that case.
In case you later on modify the behavior of your Component and need to set the state depending on new props (not current case) you might want to check getDerivedStateFromProps method.
Upvotes: 0
Reputation: 3303
Here, constructor method of Inputs
component will be called only once after it gets mounted. It'll never be called again. So, what you can do is have componentDidUpdate
method in Inputs
component and setState when the incoming count
prop is different from your present state count.
Or else, you can directly use this.props.count
in the for
as suggested by @lsa4299
Upvotes: 0
Reputation: 5912
Directly use this.props.count instead.
for (let i = 0; i < this.props.count; i++) {
Upvotes: 1