Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

props in constructor does not match props in render #5772

Closed
dbkaplun opened this issue Jan 4, 2016 · 4 comments
Closed

props in constructor does not match props in render #5772

dbkaplun opened this issue Jan 4, 2016 · 4 comments

Comments

@dbkaplun
Copy link

dbkaplun commented Jan 4, 2016

Expected:

constructor {foo: "bar", name: "Joe Schmoe"}
render {foo: "bar", name: "Joe Schmoe"}

Actual:

constructor {foo: "bar", name: "Joe Schmoe"}
render {name: "Joe Schmoe"}

Code: http://jsbin.com/gutagazaxa/1/edit?html,js,output

class HelloWorldComponent extends React.Component {
  constructor (props) {
    super(_.merge({foo: 'bar'}, props))
    console.log('constructor', this.props)
  }
  render() {
    console.log('render', this.props)
    return (      
      <h1>Hello {this.props.name}</h1>      
    )
  }
}

React.render(
  <HelloWorldComponent name="Joe Schmoe"/>,
  document.getElementById('react_example')
)
@yuchi
Copy link

yuchi commented Jan 4, 2016

Actually he’s not mutating it. He is creating a new props and passing that one to super.

I’m with you in the fact that you shouldn’t do it, but there’s no apparent reason it shouldn’t work.

@zpao
Copy link
Member

zpao commented Jan 4, 2016

See #5320 for another discussion about this (from a slightly different angle) - namely @sebmarkbage's first comment about initialization vs updates. Note: that PR was merged but was backed out because of the discussion.

If you'd like to use default values for props (foo here) then you should use the getDefaultProps API.

@zpao zpao closed this as completed Jan 4, 2016
@dbkaplun
Copy link
Author

dbkaplun commented Jan 4, 2016

@zpao I guess I'm still a little unclear.. are you saying this.props in the constructor intentionally has a different value than this.props in render()? Thanks in advance

@jimfb
Copy link
Contributor

jimfb commented Jan 4, 2016

@dbkaplun Correct - The this.props is passed into the constructor as a convince for easy access within the constructor. The component's props are controlled by React, not by the constructor, for the reasons discussed in #5320.

If you were using a more modern release of React, you should get a warning when you passed in the modified props: #5335

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants