2015-08-06 26 views
22

Bu yasal mı?React - setState bileşendeWillReceiveProps

componentWillReceiveProps: function(nextProps) { 
     if (typeof nextProps.contact != 'undefined') { 
      this.setState({forename: nextProps.contact.forename}); 
      this.setState({surname: nextProps.contact.surname}); 
      this.setState({phone: nextProps.contact.phone}); 
      this.setState({email: nextProps.contact.email}); 
     } 
    } 

Girişlerimi nasıl dolduracağımı bilmiyorum ve yine de kullanıcının girdileri düzenleyebileceğini biliyorum. Bu yüzden bu çözüme manipüle etmeye çalışmak yerine bu çözümü buldum.

Herhangi bir öneriniz var mı?

cevap

25

Kodunuz react documentation'a göre yasaldır.

Ayrıca, bu kodu getInitialState yönteminin içine koymayı da düşünebilirsiniz, another react doc, tanıtıcıdan başlatılıyor. bir setState yöntem çağrısı ile

replace birkaç çağrılar:

this.setState({forename: nextProps.contact.forename, 
       surname: nextProps.contact.surname, 
       phone: nextProps.contact.phone, 
       email: nextProps.contact.email}); 
1

Ve Babelify mümkün :)

componentWillReceiveProps({ 
    contact: { 
    forename, 
    surname, 
    phone, 
    email, 
    } = {}, 
}) { 
    if (forename !== undefined) { 
    this.setState({ 
     forename, 
     surname, 
     phone, 
     email, 
    }); 
    } 
}