2017-06-02 77 views
0

我正在創建一個反應應用程序,我需要用戶選擇他們的手機品牌和型號。他們可以在名爲「PhoneModel」的邊欄組件中選擇手機,並在另一個組件「CaseImg」中顯示與該手機相對應的圖片。 PhoneModel和CaseImg是兄弟姐妹。Reactjs - 通過更改父級狀態來傳遞兄弟之間的信息

我認爲這樣做是保持在父母的狀態信息,通過「PhoneModel」改變狀態,並把它當作道具「CaseImg」的方式

var App = React.createClass({ 
    getInitialState: function() { 
     return { 
      phoneBrand: 'Apple', 
      phoneName: 'iphone4', 
      caseModel: 'bg1' 
     }; 
    }, 

    handlePhoneSelection: function(phone, name) { 
     this.setState({ 
      phoneBrand: phone, 
      phoneName: name 
     }); 
    }, 

    render: function(){ 
     return (
      <div> 
       <div> 
        <CaseInfo /> 
        <CaseImg phoneBrand={this.state.phoneBrand} phoneName={this.state.phoneName} caseModel={this.state.caseModel} /> 
        <CustomizeBtns /> 
       </div> 
       <div> 
        <PhoneModel handlePhoneSelection={this.handlePhoneSelection} /> 
        <CaseModel /> 
        <CustomPicture/> 
       </div> 
      </div> 
     ); 
    } 
}) 

var PhoneModel = React.createClass({ 

    handlePhoneSelection: function(brand,model) { 
     this.props.handlePhoneSelection(brand,model); 
    }, 

    render: function() { 

     return (
       <div> 
        <div onClick={this.handlePhoneSelection('apple','4s')}> 
         <imgsrc="/assets/img/apple-4s.png" /> 
        </div> 
        <div onClick={this.handlePhoneSelection('apple','7s')}> 
         <imgsrc="/assets/img/apple-7s.png" /> 
        </div> 
        <div onClick={this.handlePhoneSelection('apple','7splus')}> 
         <imgsrc="/assets/img/apple-7splus.png" /> 
        </div> 
       </div> 
     ); 
     } 
}) 

我已經嘗試了很多不同的解決方案我對相關問題找到,但繼續得到同樣的錯誤:

setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`. 

PS:這個程序很簡單,我不希望使用助焊劑或終極版。

編輯:固定提到的錯字,這是不存在於我的原代碼

+0

我敢肯定,這是你的問題中一個錯字,但你錯過了你的回調右括號,'this.handlePhoneSelection(「蘋果','4s',看起來會立即被調用,這會導致無限的渲染週期。 – lux

+0

你正在做的正確,但像@lux指出,你有錯別字最有可能導致錯誤 –

+0

其實這是我在複製代碼時犯的一個錯誤,原來的代碼是 –

回答

0

的onclick點的this.handlePhoneSelection('apple','4s')的結果,而不是handlePhoneSelection功能:

<div onClick={this.handlePhoneSelection('apple','4s')}>

所以裏面的渲染方法,在渲染過程中觸發this.handlePhoneSelection('apple','4s')並嘗試更新狀態。

而你需要做的這個代替:

<div onClick={() => this.handlePhoneSelection('apple','4s')}>

+0

,我試過了,但是出現這個錯誤:'''''''''''''''''''''''''''''''作爲一個函數,而不是類型布爾「...也許我應該綁定(這)在父組件? –

+0

這個錯誤信息沒有意義......'()=> this.handlePhoneSelection('apple','4s')'不能是布爾類型? – wesley6j

+0

是的,我不明白。我猜想子組件中的處理函數由於某種原因返回false –