2017-08-31 57 views
0

我在我的應用程序下面的代碼...試圖調用地圖,但它不是一個數組

componentWillMount(){ 
    this.ref = base.syncState('/tasks', { 
     context: this, 
     state: 'tasks' 
    }); 
    } 

... 
renderTasks() { 
     return this.state.tasks.map(name => (
     <Task 
      key={name} 
      name={name} 
      removeTask={this.removeTask} 
     /> 
    )); 
    } 
     render() { 
     return (
     <div className="TaskList"> 
      <h3>TODO List</h3> 
      {this.renderTasks()} 
      <TaskInput addTask={this.addTask}/> 
     </div> 
    ); 
    } 
} 

我的應用程序得到的錯誤是... TypeError: this.state.tasks.map is not a function我的理解是,因爲任務不是一個數組,但我不知道爲什麼?如果我在renderTasks中添加console.log(this.state.tasks),它會顯示兩次,第一次是[],但下一次是{}。我也不明白。這裏是完整的代碼:https://gist.github.com/marklocklear/e88f75e7e973f67490f6b3034c9eeeff

在此先感謝!

+1

什麼是'base.syncState'在做什麼? –

回答

0

首先在構造函數中,您的tasks設置爲[],因爲此時this.props.tasks未定義。可能在此之後,您正在向API發出異步請求,返回值爲{}。當props更新時,您的component正在重新渲染。您必須將您的調用更新到API並確保它返回數組。如果沒有base文件的內容,不能再多說什麼。

+0

謝謝!這很有幫助。我用base.js的內容更新了要點 – Lumbee

0

這是一個非常簡單的修復。我只需要將asArray屬性添加到compnentWillMount並且它工作。

componentWillMount(){ 
    this.ref = base.syncState('/taks', { 
     context: this, 
     state: 'tasks', 
     asArray: true 
    }); 
    } 
相關問題