How to easily pass data from child to root in reactjs?
-
20-12-2019 - |
Question
I have a comment box like this:
I have bound all actions to CommentBox component, there is a decComment action to handle Delete
event in each comment.
Everytime when i click the delete
button in Comment
I need to pass the commentId
of Comment
to CommentList
to CommentBox
and then CommentBox
updates comment data, removes that comment from comments data and re-renders the comment list.
Here is some code:
var Comment = React.createClass({
handleDel: function() {
var cid = this.props.cid;
this.props.onDel(cid);
return false;
},
render: function() {
return (
<div key={this.props.cid}>
<a onClick={this.handleDel}>Del</a>
</div>
);
}
});
var CommentList = React.createClass({
handleDel: function(cid) {
this.props.onDel(cid);
},
render: function() {
var commentNodes = this.props.data.map(function(c) {
return <Comment cid={c.id} onDel={this.handleDel} />
}.bind(this));
return (
<div className="comments">
{commentNodes}
</div>
)
}
});
var CommentBox = React.createClass({
... ...
delComment: function (cid){
function del(data) {
$.ajax({
url: url,
type: 'delete',
dataType: 'json',
data: data,
success: function (e) {
if (e.retcode === 0) {
that.setState({
data: e.data
});
} else {
alert(e.error);
}
}
});
}
if (window.confirm('You Sure ?')) {
del();
}
},
... ...
})
This process too verbose! Is there any easy way to do this?
Solution
You can also do a partial application of the a handler, like so:
<Comment onDel={this.handleDel.bind(null, c.id)} />
When this.handleDel
is called, c.id
will be passed as the first argument. You can also shorten it by removing CommentList.handleDel
and just doing
<Comment onDel={this.props.onDel.bind(null, c.id)} />
For a little more info on this topic, see Communicate Between Components in the React docs.
OTHER TIPS
You can also try to manage a global application state that will be available to all components, passed by props.
On every change to the application state, you can re-render the whole thing.
As you rerender from the top-level component you may try to optimize with shouldComponentUpdate
. I didn't test that and don't know if it is manageable for a large application however.
Also, take a look at how Om is optimizing shouldComponentUpdate
by using immutable data structures.