Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
React - State not updated

Here I try to set state.autocomplete to 'hello' and then print it, but state seems to be null. How can that be when I just updated the state using setState? data is set as a global variable.

  var data = {
    populate_at: ['web_start', 'web_end'],
    autocomplete_from: ['customer_name', 'customer_address']
  };


  var AutocompleteFromCheckboxes = React.createClass({
    handleChange: function(e) {
      this.setState( { autocomplete_from: 'event.target.value' } );
      console.log('autocompleteFrom state: ', this.state.autocomplete_from);
      // ^  => Uncaught TypeError: Cannot read property 'autocomplete_from' of null
      return 1;
    },
    render: function() {
      var autocompleteFrom = this.props.autocomplete_from.map(function(value) {
        return (
          <label for={value}>
            <input type="checkbox" name={value} value="{value}"
              onChange={this.handleChange.bind(this)}
              ref="autocomplete-from"/>
            {value}
          </label>
        );
      }, this);
      return (
        <div className="autocomplete-from">
          {autocompleteFrom}
        </div>
      );
    }
  });

  var DynamicForm = React.createClass({
    getInitialState: function() {
      return {
        name              : null,
        populate_at       : null,
        same_as           : null,
        autocomplete_from : "not set",
        title             : null
      };
    },
    saveAndContinue: function(e) {
      e.preventDefault();
      var data = {
        name     : this.refs.name.getDOMNode().value,
      };
      console.log('data: ' + data.name);
    },

    render: function() {
      return (
          <AutocompleteFromCheckboxes
            autocomplete_from={this.props.data.autocomplete_from} />
      );
    }
  });


  var mountpoint = document.getElementById('dynamic-form');
  if ( mountpoint ) {
    React.render(<DynamicForm data={data} />, mountpoint);
  }

});
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

From the reactjs docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

https://facebook.github.io/react/docs/component-api.html

What you can do is pass a callback function to setState which is triggered once the state has been updated:

this.setState(
    {autocomplete_from: ...}, 
    function () {
        ... at this point the state of the component is set ...
    }
)
over 4 years ago · Santiago Trujillo Relatório

0

You need to set the initial state of your component, try adding the following to the top of your component.

getInitialState: function() {
  return {
   autocomplete_from: ''
  };
}

EDIT:

In your DynamicFrom component you have:

render: function() {
  return (
      <AutocompleteFromCheckboxes
        autocomplete_from={this.props.data.autocomplete_from} />
  );
}

Since you are trying to reference the state you should write

autocomplete_form={this.state.autocomplete_from}

Also you are trying to set the state from a child component and it should not directly modify state. The best way to approach this is to pass down a function from DynamicFrom(holds the state) to AutocompleteFromCheckboxes. Like so.

var DynamicForm = React.createClass({
    handleChange: function(value) {
       this.setState({autocompelete_from: value});
    },
    render: function() {
       return(
          <AutocompleteFromCheckboxes 
            autocomplete_from={this.state.autocomplete_from}
            handleChange={this.handleChange} 
          />
       );
    },
    ....
});

Then call that function in your child component

AutocompleteFromCheckboxes = React.createClass({
    ....
    onChange={this.handleChange}
    ....
    handleChange: function(e) {
     this.props.handleChange(e.target.value);
    }
});
over 4 years ago · Santiago Trujillo Relatório

0

To see updated state value after doing setState you should do something like below

 this.setState( { autocomplete_from: 'event.target.value' }, () => { 
    console.log(this.state.autocomplete_from);//this will print the updated state value
 });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda