简体   繁体   中英

ReactJS Form input initial state undefined

I have a user form which pulls in data from a prop and populates each input field with its value. When I click to open an empty form (as if I'm adding a new user) I get the error TypeError: Cannot read property 'language' of undefined .

State:

   ...  
   constructor(props) {
    super(props);
    this.state = {
    language: this.props.user.language || '',
    description: this.props.user.description || ''
   }
   handleChange = (e) => {
    e.preventDefault();
    this.setState({[e.target.name]: e.target.value});
    console.log(this.state);
   }
   ...
  }

Input field:

<input type="text" placeholder="Language..." id="language" name="language" value={this.state.language} onChange={this.handleChange}/>

It should show the value field as empty if it can't read the value of the user object. I've tried setting the or value to null but this throws the same error.

Thanks

You can check this.props.user like this to avoid the error :

this.state = {
    language: this.props.user ? this.props.user.language : '',
    description: this.props.user ? this.props.user.description : ''
}

This is the inline operation using the ternary operators equivalent to :

if (this.props.user) {
    return this.props.user.language;
} else {
    return '';
}

I'd use componentWillReceiveProps() for this because if you change the user in the Parent component it would change the state in the Child as well because it will trigger componentWillReceiveProps() . Also, check if this.props.user exists on your constructor.

...
constructor(props) {
    super(props);
    this.state = {
    language: this.props.user && this.props.user.language || '',
    description: this.props.user && this.props.user.description || ''
   }
...
componentWillReceiveProps(nextProps) {
    if (nextProps.user) {
        this.setState({
            language: nextProps.user.language,
            description: nextProps.user.description
        })
    }
}

This is what I would try.

constructor(props) {
    super(props);
    this.state = {
        language: '',
        description: ''
    }
}

componentDidMount() {
    if (this.props.user) {
        this.setState({
            language: this.props.user.language,
            description: this.props.user.description
        })
    }
}

handleChange = (e) => {
    e.preventDefault();
    this.setState({[e.target.name]: e.target.value});
    console.log(this.state);
}

You can use lodash method get to set the field as empty if it cant the user is undefined like so _.get(this.props, 'user.language','')

but it looks like you are not passing a user as a prop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM