javascript - I don't understand how components are mounted -
i use pattern container/representational components.
have cardcontainer
component fetch data server , pass card
component
container component:
class cardcontainer extends component { state = { 'card': null } componentdidmount() { fetch(`${baseurl}/api/cards/${this.props.params._id}/`) .then(res => res.json()) .then(card => this.setstate({'card': card})) } render() { return <carddetail card={this.state.card} /> }
representational component:
class carddetail extends component { render() { return ( <div> {this.props.card._id} </div> ) } }
in case have error:
uncaught typeerror: cannot read property '_id' of null
so render method of child called before componentdidmount
of parrent.
in case when pass stateless function component child works fine:
const functionchild = props => <h1>{props._id}</h1> class carddetail extends component { render() { return ( <div> <functionchild {...this.props.card} /> </div> ) } }
i use console.log in components render
, in componentdidmount
method understand method resolution:
- mount container
- mount child
- mount function child
- didmount container method
so componentdidmount
still called last works fine. please explain missing.
reason is, defined card value null
, , accessing value of id, that's why throwing error :
can not access property id of null
because fetching data api
, asynchronous call
, take time return
data, until didn't data, value of card null
.
one way of fixing is, initialise card {}
instead of null
, this:
class cardcontainer extends component { state = { 'card': {} //change } componentdidmount() { fetch(`${baseurl}/api/cards/${this.props.params._id}/`) .then(res => res.json()) .then(card => this.setstate({'card': card})) } render() { return <carddetail card={this.state.card} /> }
or put check inside child component before accessing id value, this:
class carddetail extends component { render() { return ( <div> {this.props.card && this.props.card._id} </div> ) } }
Comments
Post a Comment