2
Problems when passing props to component state, when in component do console.log(this)
The client props is there with all the fields, the more when I do console.log(this.props)
he shows me the empty state. the this.state.cliente2
is always empty. Where I’m going wrong. I’ve spent hours trying to find 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>
)
}
}
+1
- you could also add theconstructor
in the explanation and mention that it too is run only once, hence thatthis.state = {cliente2: this.props.cliente };
is run before App runs thecomponentDidMount
– Sergio