我正在創建一個反應應用程序,我需要用戶選擇他們的手機品牌和型號。他們可以在名爲「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:這個程序很簡單,我不希望使用助焊劑或終極版。
編輯:固定提到的錯字,這是不存在於我的原代碼
我敢肯定,這是你的問題中一個錯字,但你錯過了你的回調右括號,'this.handlePhoneSelection(「蘋果','4s',看起來會立即被調用,這會導致無限的渲染週期。 – lux
你正在做的正確,但像@lux指出,你有錯別字最有可能導致錯誤 –
其實這是我在複製代碼時犯的一個錯誤,原來的代碼是 –