Answer the question
In order to leave comments, you need to log in
How to change the state of a child component from outside in react?
How it is possible to change child state from parent functions?
For example, there are sockets, while receiving a message from the socket ( socket.on('test', function(data)..... ) you need to put this message in the history of the Dialog component. It is not good to hang it inside the dialog, because .if in data.dialog_id from the socket != Dialog.dialog_id I don't need to update the history of correspondence.
Apparently I don't understand anything in react, the first day I've been digging, I've rummaged through the stack.. Kind people help)
var Dialog = React.createClass({
getInitialState() {
return {
id: 0,
history: [],
};
},
_insertMessage(data){
if(!data) data = {user: 1, text: 'test'};
var history = this.state.history;
history.push(data)
this.setState({ history: history })
},
render() {
return (
<div>
<h3>Диалог: {this.state.id}</h3>
<div>
{
this.state.history.map((message, i) => {
return (
<Message
key={i}
user={message.user}
text={message.text}
/>
);
})
}
</div>
</div>
);
}
});
var App = React.createClass({
componentDidMount() {
socket.on('test', function(data){
}
},
render() {
return (
<div>
<Dialog />
</div>
);
}
});
ReactDOM.render(<App />, document.getElementById('app'));
Answer the question
In order to leave comments, you need to log in
In theory, in this piece you can change the state
componentDidMount() {
socket.on('test', function(data){
this.setState({/* ....... */});
}
}.bind(this),
render() {
return (
<div>
<Dialog someval={this.state.someval} />
</div>
);
}
Pavel Shcheglov 's
answer is correct in principle, except that you are in this place
componentDidMount() {
socket.on('test', function(data){
this.setState({/* ....... */});
}
}.bind(this),
this.setState is not a function
, outside callback-а
you have to redefine this, for example, let self = this;
and inside the function change this.setState
to self.setState
. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question