I have 2 components. The first PageExample is a container that goes to api for data, the data that comes in the api are written to the state.

The second MyModal is a normal component in which data from the parent this.state is transmitted through the props.

As in MyModal, correctly assign the transferred props to the local state. That is, I want the transferred propy to become the state of MyModal. Is it possible? If so, in which method is it more correct to do this, in the constructor or in componentDidMount, etc.? thank

    1 answer 1

    Yes, you can do all this as you wish. Here, for example, in the parent PageExample you send props data that you received from the API and recorded in the dataAPI state in the MyModal component.

    Suppose there is a function in PageExample in which we receive data and put it into the state:

     loadDatafromAPI() { // тут какой-то код получения данных (к примеру) let data = ... // и запись этих данных в state this.setState({ dataAPI: data }); } 

    And then inside PageExample you create your MyModal component to which you transfer this data via props :

     <MyModal data={this.state.dataAPI} /> 

    and already inside your MyModal , in the constructor, you can assign them to the local state:

     constructor(props) { super(props); this.state = { dataAPI: props.data } } 

    As for componentDidMount , it is possible in it, for example, here: componentDidMount () recommends downloading data from a remote endpoint (for network requests) inside it. However, calling setState({..}) in this method will cause additional rendering, but this will happen before the browser refreshes the screen. I would write in the designer.

    • The constructor is called only once when the component is initialized. At the time of the call, api has not yet had time to give the data, state is empty. Maybe there is some kind of lifecycle method in which you can do this.setState ({data: this.props.dataApi})? - abakan
    • one
      @abakan, yeah, there is such a possibility through componentWillReceiveProps but it is outdated in the new version of the reactant ... although you can use getDerivedStateFromProps . Link: componentWillReceiveProps (nextProps) - Denis Bubnov
    • What you need, thank you - abakan
    • @abakan and you can still use the props parent simply, in case you need to update the data, pass the callback to the update props through the props . Well it is, by the way about how to do more. - Denis Bubnov
    • Now it is done. I just changed the data in the modal data and changed on the page, that is, in the parent. I wanted to get rid of it) - abakan