2015-09-08 1 views
0

В этом реактивном коде я пытаюсь установить данные в текущее состояние. После установки данных в состояние мне нужно использовать его в таблице фиксированных данных. Чтобы достичь этого , я написал, как показано ниже. Основная проблема заключается в том, что оператор рядом с «this.setState» в componentDidMount не выполняется/не достигает, где мне нужно вызвать функцию таблицы данных. вот мой код:Заявление не достигнуто после установки состояния в реакции ES-6

 export default class Main extends React.Component { 
     constructor(props) { 
      super(props); 
      this.state = { 
       result: [], 
       loading: false, 
       filteredRows: null, 
       filterBy: null, 
      }; 
     } 
     getZipData() { 
      //Here i got the data from server 
     } 
     componentDidMount() { 
      this.getZipData().then((data)=>{ 
       console.log("data:"+data.length); 
       this.setState({result:data,loading:true}); //state successfully set here. 
       console.log("result:*******************"+this.state.result.length); //this console is not printed 
this._filterRowsBy(this.state.filterBy) 
      }); 

     }; 
     _rowGetter(rowIndex){ 
      alert("row Getter"); 
      return this.state.filteredRows[rowIndex]; 
     } 
     _filterRowsBy(filterBy){ 
      var rows = this.state.result.slice(); 
      var filteredRows = filterBy ? rows.filter((row)=>{ 
       return row.RecNo.toLowerCase().indexOf(filterBy.toLowerCase()) >= 0 
      }) : rows; 
      this.setState({ 
       filterRows, 
       filterBy, 
      }) 
     } 
     _onFilterChange(e){ 
      this._filterRowsBy(e.target.value); 
     } 
     render() { 
      if(this.state.loading==false) { 
       return (
        <div className="row-fluid"> 
         <img className="col-sm-6 col-sm-offset-3 col-xs-6 col-xs-offset-3" 
          src="http://www.preciseleads.com/images/loading_animation.gif"/> 
        </div> 
       ) 
      } 
      else{ 
       console.log("result:////////////////////"+this.state.result.length); //this console is printed 
       console.log("loading completed"); 
       return(
        <div> 
         <!-- fixed data table code goes here --> 
        </div> 
       ) 
      } 

     } 
    } 

состояние успешно обновляется, но после этого заявления не достигнуто, В componentDidMount, любая помощь очень ценится.

+0

Я не думаю, что это конкретная проблема электрона , –

ответ

1

Добавить обработчик улова к вашему обещанию. Я полагаю, вы получаете ошибку.

+0

yah, тогда я получил эту ошибку: Invariant Violation: child тип e должен быть или

+0

Так вот проблема. Решите, и все будет работать так, как ожидалось. – gyzerok

0

Привет там, может быть, это ваша проблема,

Facebook:

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. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.

this.setState({result:data,loading:true},() => { 
    // Your logic 
    }); 

второй аргумент функции обратного вызова, которая вызывается после того, как состояние установлено.

Надеется, что это помогает :)

Edit: я не видел инвариантную ошибки (Из комментария, может у обеспечить полную ошибку)

Смежные вопросы