Answer the question
In order to leave comments, you need to log in
How to raise the state if it needs to be done every time the state of the child is updated?
Good afternoon.
I know the principle of raising states. react 16.5.1.
There is an application which consists of the Parent and 2 descendants. In one child, I have some calculations going on, that is, the calculation method is executed when the component is mounted and with every change in the inputs. This method changes the state of this component. It is necessary for me that this state at each change is forwarded above to the parent, and transferred to the 2nd descendant.
It would be logical to do this in componentDidUpdate, but then I will get Maximum update depth exceeded, because in the method for raising I use setState for the parent to pass next. I don't understand what to do here.
Answer the question
In order to leave comments, you need to log in
Store all form state in the parent and pass a callback to the child:
class Child extends Component {
render() {
const { handleChange } = this.props;
return (
<Wrapper>
<SomeInput onChange={handleChange} />
</Wrapper>
);
}
}
handleChange = e => {
const { name, value } = this.props;
this.setState({ [name]: value }, this.calculate);
};
Store the value of the inputs in the parent state and pass it to the props of the children.
class Parent extends React.Component {
state = {
inputFoo: '',
inputBaz: ''
};
handleChangeInput = (inputName, value) => {
this.setState({
[inputName]: value
})
}
render() {
const { inputFoo, inputBaz } = this.state;
return (
<div>
<Children1
inputFoo={inputFoo}
inputBaz={inputBaz}
onChangeInput={this.handleChangeInput}
/>
<Children2
inputFoo={inputFoo}
inputBaz={inputBaz}
/>
</div>
);
}
}
class Chidlren1 extends React.Component {
handleInputChange = event => {
const {name, value} = event.target
this.props.onChangeInput(name, value);
}
render() {
const { inputFoo, inputBaz } = this.props;
return (
<div>
<input
type="text"
name="inputFoo"
value={inputFoo}
onChange={this.handleChangeInput}
/>
<input
type="text"
name="inputBaz"
value={inputBaz}
onChange={this.handleChangeInput}
/>
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question