javascript - React.js confuse with 'two children with the same key' -
i'm using react mounting 2 same components on page,
var selectbox = react.createclass({ getdefaultprops: function() { return { value: [] }; }, getinitialstate: function() { return {checked: this.props.value,count: 1}; }, handleclick: function() { var opt = this.state.checked; opt.push({id: this.state.count, name: this.state.count}); this.setstate({checked: opt, count: this.state.count + 1}); }, render: function() { var = this; var options = this.state.checked.map(item => <option key={'checked-' + that.props.name + item.id} value={item.id}>{item.name}</option>); return ( <div> <select multiple={true}> {options} </select> <button type="button" onclick={this.handleclick}>add</button> </div> ); } }); react.render( <selectbox name='one'/>, document.getelementbyid('one') ); react.render( <selectbox name='two'/>, document.getelementbyid('two') );
then click button of 'one', it's alright, when click button of 'two', of 'one' crop in 'two',why?? make me confuse. console show:
warning: flattenchildren(...): encountered 2 children same key, `.$checked-two1`. child keys must unique; when 2 children share key, first child used.
but change
var = [{id: 5, name: 5}]; react.render( <selectbox name='one' value={a}/>, document.getelementbyid('one') );
it work properly. happenned?is there wrong or it's bug?
oh,i find real reason,getdefaultprops
called once , cached, complex objects returned getdefaultprops()
shared across instances, not copied, selectbox components without explicit value prop passed share same checked array reference in state. in case, should write:
getinitialstate: function() { var tmp = this.props.value.concat(); return {checked: tmp, count: 1}; },
Comments
Post a Comment