Problems passing props to state of React component

2

Problems passing props to the state of the component, when in the component I make console.log(this) the props client is there with all fields, but when I do console.log(this.props) it shows me the empty state. this.state.cliente2 is always empty. Where am I going wrong. I've spent hours trying to figure it out.

  

app.js

import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import Lista from './Lista'

class App extends Component {

  constructor () {
    super()
    this.state = {cliente: {}}
  }

  componentDidMount () {
    let ClienteJson = {
      'id': 1,
      'cadastro': '2017-04-06T01:07:48.000Z',
      'nome': 'Alexandre',
      'email': '[email protected]',
      'cidade': 'PIRAPORA',
      'estado': 'MG'
    }

    this.setState({cliente: ClienteJson})
  }

  render () {
    return (
      <div className='App'>
        <div className='App-header'>
          <img src={logo} className='App-logo' alt='logo' />
          <h2>Welcome to React {this.state.cliente.nome}</h2>
        </div>

        <Lista cliente={this.state.cliente} />

        <p className='App-intro' />
      </div>
    )
  }
}

export default App
  

component: List

import React, { Component } from 'react'

export default class Lista extends Component {
  constructor (props) {
    super(props);
    this.state = {cliente2: this.props.cliente };
    console.log(this);
  }

  componentDidMount (prors) {

  }

  render () {
    return (
      <div>
        <ul> <li> {this.state.cliente2.nome} </li> </ul>
        <ul> <li> {this.props.cliente.nome} </li> </ul>
      </div>
    )
  }
}
    
asked by anonymous 23.09.2017 / 01:41

1 answer

2

The problem is occurring because you are updating the value after the component is rendered.

  

componentWillMount: is called once, both client side and server before rendering.

     

componentDidMount: called once, only on the client side, after rendering.

     

shouldComponentUpdate: called after rendering when properties and state is being defined. It returns true or false to tell if the element should update.

     

componentWillUnmount: called when we want to unmount the component.

Then in your file app.js change componentDidMount to componentWillMount thus leaving:

componentWillMount() {
    let ClienteJson = {
        'id': 1,
        'cadastro': '2017-04-06T01:07:48.000Z',
        'nome': 'Alexandre',
        'email': '[email protected]',
        'cidade': 'PIRAPORA',
        'estado': 'MG'
    }
    this.setState({cliente: ClienteJson})
}

You can see it working in codesandbox .

Update

As well remembered by friend Sergio, the constructor method is only called once, so all state defined within this method is executed before the componentDidMount method.

    
23.09.2017 / 03:07