Reactjs - 通过更改父状态在兄弟姐妹之间传递信息

时间:2017-06-02 17:27:11

标签: reactjs

我正在创建一个反应应用,我需要用户选择他们的手机品牌和型号。他们可以在名为“PhoneModel”的侧边栏组件中选择他们的手机,并在另一个组件“CaseImg”中显示与该手机对应的图片。 PhoneModel和CaseImg是兄弟姐妹。

我想这样做的方法是将这些信息保存在父级状态,通过“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:这个应用很简单,我不想使用Flux或Redux。

编辑:修正了我提到的错字,这在原始代码中没有出现

1 个答案:

答案 0 :(得分:0)

onClick指向this.handlePhoneSelection('apple','4s')而不是handlePhoneSelection函数的结果:

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

因此在render方法中,this.handlePhoneSelection('apple','4s')在渲染过程中被触发并尝试更新状态。

而你需要这样做:

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