2017-05-08 34 views
1

我有下面的代碼。渲染器中的console.log實際上給出數組長度爲3.但是沒有顯示。componentDidMount未設定狀態或重新呈現

AuthorApi.js

//This file is mocking a web API by hitting hard coded data. 
var authors = require('./authorData').authors; 
var _ = require('lodash'); 

//This would be performed on the server in a real app. Just stubbing in. 
var _generateId = function(author) { 
    return author.firstName.toLowerCase() + '-' + author.lastName.toLowerCase(); 
}; 

var _clone = function(item) { 
    return JSON.parse(JSON.stringify(item)); //return cloned copy so that the item is passed by value instead of by reference 
}; 

var AuthorApi = { 
    getAllAuthors: function() { 
     console.log("Inside getAll"); 
     console.log("Authors length is : " + authors.length); 
     return _clone(authors); 
    }, 

    getAuthorById: function(id) { 
     var author = _.find(authors, {id: id}); 
     return _clone(author); 
    }, 

    saveAuthor: function(author) { 
     //pretend an ajax call to web api is made here 
     console.log('Pretend this just saved the author to the DB via AJAX call...'); 

     if (author.id) { 
      var existingAuthorIndex = _.indexOf(authors, _.find(authors, {id: author.id})); 
      authors.splice(existingAuthorIndex, 1, author); 
     } else { 
      //Just simulating creation here. 
      //The server would generate ids for new authors in a real app. 
      //Cloning so copy returned is passed by value rather than by reference. 
      author.id = _generateId(author); 
      authors.push(_clone(author)); 
     } 

     return author; 
    }, 

    deleteAuthor: function(id) { 
     console.log('Pretend this just deleted the author from the DB via an AJAX call...'); 
     _.remove(authors, { id: id}); 
    } 
}; 

module.exports = AuthorApi; 

請讓我知道我做錯了。

+0

解決在使用之前你的諾言'setState' – lux

+0

您好我試圖用uthorApi.getAllAuthors() 。然後(RES => this.setState({作者:RES}))卻得到了錯誤,則說的是不是一個函數。我用AuthorAPI代碼更新了這個問題。 –

回答

2

嘗試在地圖中添加返回。

this.state.authors.map((author) => { 
         return (<tr key={author.id}> 
          <td><a href={"/#authors/" + author.id}>{author.id}</a></td> 
          <td>{author.firstName} {author.lastName}</td> 
         </tr>) 
        }, this)} 
+0

是的,它的工作。謝謝:) –

+0

如果我必須做一個實際的ajax調用,我仍然應該在componentDidMount()方法中執行它? –

相關問題