2017-06-28 52 views
0

開發者!有人能幫助我嗎? 我試圖設置state從流星數據做出反應,並從輸入編輯這個state數據,它看起來像設置來自流星數據的反應狀態


class Profile extends Component{ 
    constructor(props){ 
    super(props); 
    this.editProfileBind = this.editProfile.bind(this); 
    this.testEmailBind = this.testEmail.bind(this); } 

    testEmail(e){ 
    const input = e.target; 
    this.setState({ 
     email: input.value 
    }); 
    input.value = this.state.email; 
    } 

    editProfile(e){ 
     e.preventDefault(); 
    } 

    render(){ 
    return(
     <form className="col-md-4 col-xs-6" 
      onSubmit={this.editProfileBind}> 
      <input type="email" 
        onChange={this.testEmailBind} 
        value={this.props.email || ''} 
       /> 
      <button type="submit">Submit</button> 
     </form> 
    ) 
} 
} // end component 

export default createContainer(() => { 
    const user = Meteor.user(); 
    const email = user.emails && user.emails[0].address; 

    return { email }; 
}, Profile); 

您能否提供我怎麼可以設置this.state.email輸入,而不是this.props.email?謝謝!

回答

3

夫婦問題與代碼:

1 Intialize狀態道具

在構造函數中,你需要你的初始狀態設置爲email道具在傳遞

。 2.輸入value應該等於this.state.email

值isn不會更新,因爲您正在設置傳入的道具的值(不會更改),而不是email,因此您的testEmail函數正在更新。

3.更新狀態與新道具

您需要添加一個componentWillReceiveProps功能,當新的數據被傳遞到Profile組件,更新您的email狀態。

Profile成分應該是這樣的:

class Profile extends Component{ 
    constructor(props){ 
    super(props); 
    this.editProfileBind = this.editProfile.bind(this); 
    this.testEmailBind = this.testEmail.bind(this); 
    this.state = { 
     email: props.email 
    } 
    } 

    testEmail(e){ 
    const input = e.target; 
    this.setState({ 
     email: input.value 
    }); 
    } 

    editProfile(e){ 
     e.preventDefault(); 
    } 

    componentWillReceiveProps(nextProps){ 
    this.setState({ 
     email: nextProps.email 
    }); 
    } 

    render(){ 
    return(
     <form className="col-md-4 col-xs-6" 
      onSubmit={this.editProfileBind}> 
      <input type="email" 
        onChange={this.testEmailBind} 
        value={this.state.email} 
       /> 
      <button type="submit">Submit</button> 
     </form> 
    ) 
} 
} // end component 

export default createContainer(() => { 
    const user = Meteor.user(); 
    const email = user.emails && user.emails[0].address; 

    return { email }; 
}, Profile); 
+0

感謝@Chase,它的作品!所以有關靜態電子郵件的原因是我使用道具...謝謝,還可以提供一些材料來了解React? –

+0

太棒了!嘿追逐,有條件地設置componentWillReceiveProps中的狀態有問題。 也就是說檢查加載是否完成,然後才設置它。 –

+0

@FabianBosler這樣做很好,但最好在父組件'render'中進行'加載'檢查。 –