javascript - React component could not sync props which created by dynamic ReactDOM.render -
when use react+redux+immutable, issue: component created dynamic way, when props change, component not rerender. react bug?
i deleted business code, react code here: http://codepen.io/anon/pen/gomoez
or below:
import react 'react' import reactdom 'react-dom' class extends react.component { constructor(props) { super(props); this.state = { name: 'tom' } } dynamic() { reactdom.render(<b name={this.state.name} changename={this.changename.bind(this)} type={false}/>, document.getelementbyid('box')) } changename() { this.setstate({ name: 'tom->' + date.now() }); } render() { return <div> top name: {this.state.name} <b name={this.state.name} changename={this.changename.bind(this)} type={true}/> <div id="box"></div> <button onclick={this.dynamic.bind(this)}>dynamic add component</button> </div> } } class b extends react.component { render() { return <div> {this.props.type ? '(a)as sub component' : '(b)create reactdom.render'} - name:【{this.props.name}】 <button onclick={this.props.changename}>change name</button> </div> } } reactdom.render( <a/>, document.getelementbyid('example') );
it not bug, not react-way want. each call a.render
overwrite <div id="box">...</div>
deleting elements added a.dynamic
.
more idiomatic way add flag, set in onclick
handler , use in a.render
decide if <div id="box">
should empty or not.
see edited code on codepen: http://codepen.io/anon/pen/obgodn
relevant parts here:
class extends react.component { constructor(props) { super(props); this.state = { name: 'tom', showb: false // new flag } } changename() { this.setstate({ name: 'tom->' + date.now() }); } // changing flag on button click showb() { this.setstate({showb: true}) } render() { // `dynamic` contain component b after button clicked var dynamic; if(this.state.showb) { dynamic = <b name = {this.state.name} changename = {this.changename.bind(this)} type = {false} /> } return <div> top name: {this.state.name} <b name = {this.state.name} changename = {this.changename.bind(this)} type = {true}/> <div>{dynamic}</div> <button onclick = {this.showb.bind(this)}> dynamic add component </button> </div> } }
update
can still use approach, need manually update dynamically created component.
e.g. can manually rerender in changename
function.
changename() { this.setstate({ name: 'tom->' + date.now() }, this.dynamic.bind(this)); }
note, this.dynamic
passed second argument this.setstate
ensures called when state updated. adding this.dynamic()
after this.setstate({...})
use not-yet-updated state.
codepen here: http://codepen.io/anon/pen/epwovv
Comments
Post a Comment