Suppose there is a tree list> list item-> form-> submit button. I need to re-render the tree again when I click on submit, how can I do it?
1 answer
If each of the elements you describe represents a separate component, then you can pass from the top-level component a function that changes its state. This technique is called lifting the state, you can read more here .
- I apparently can not understand. Should I transfer from list to element, from element to form of the list itself? Then this state in this.props will come to me in the form, how can I change it later? - Enkei
- one@Enkei no, you need to pass the function declared in the component of the parent (the list in your case) and changing its state through props, and then call it in the necessary child component - Regent
- @Enkei in the parent component you can define the function onClick = () => this.setState ({toggle: true}); Then pass it to the child components through the props and call at the right time. - Smolin Pavel
- @ smolin-pavel Okay, I did it, everything works. Now the question is different: I make a request to the server in componentDidMount in the list component, it changes state several times. When I change this.state.toggle, componentDidMount is not rerun and does not receive new data from the server. In which method do I need to transfer the request to the server so that it will be executed every time the state is updated? - Enkei
- @Enkei that's right, componentDidMount only runs once. You can use componentDidMount (for the first render) and componentDidUpdate (for future updates). Read more - here.reactjs.org/docs/react-component.html#componentdidupdate - Smolin Pavel
|