E
E
exxagw2016-10-21 13:06:00
JavaScript
exxagw, 2016-10-21 13:06:00

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

3 answer(s)
P
Pavel Shcheglov, 2016-10-21
@webfarrock

In theory, in this piece you can change the state

componentDidMount() {
    socket.on('test', function(data){
      this.setState({/* ....... */});
    }
  }.bind(this),

And transfer the changed sate (the desired piece through props)
render() {
    return (
      <div>
        <Dialog someval={this.state.someval} />
      </div>
    );
  }

A
Anton, 2016-10-21
@SPAHI4

There are props for this

D
Dzhakhar Ukhaev, 2016-10-22
@dzhakhar1209

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),

get an error this.setState is not a function, outside callback-аyou have to redefine this, for example, let self = this;and inside the function change this.setStateto self.setState.
This will happen because each function has its own context, which you access via this, and in the callback, this no longer refers to your component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question