我是reactJS的新手,我无法找到为什么反应无法使用此声明加载authorApi
var AuthorApi = require('../../ api / authorApi');
这是我的项目中的剪辑
src / components / authors / author.js code
'use strict';
var React = require('react');
var AuthorApi = require('../api/authorApi');
var Authors = React.createClass({
getInitialState: function () {
return {
authors: []
};
},
componentWillMount: function () {
this.setState({ authors: AuthorApi.getAllAuthors() });
},
render: function () {
var createAuthorRow = function (author) {
return (
<tr key={author.id}>
<td>
<a href={"/#authors/" + author.id}>{author.id}</a>
</td>
<td>
{author.firstName} {author.lastName}
</td>
</tr>
);
};
return (
<div>
<h1>Authors</h1>
<table className="table">
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
{this.state.authors.map(createAuthorRow, this)}
</tbody>
</table>
</div>
);
}
});
module.exports = Authors;
src / api / authorApi.js代码
"use strict";
//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() {
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(author);
}
return _clone(author);
},
deleteAuthor: function(id) {
console.log('Pretend this just deleted the author from the DB via an AJAX call...');
_.remove(authors, { id: id});
}
};
这里是src / api / authorData.js代码
module.exports = {
authors:
[
{
id: 'cory-house',
firstName: 'Cory',
lastName: 'House'
},
{
id: 'scott-allen',
firstName: 'Scott',
lastName: 'Allen'
},
{
id: 'dan-wahlin',
firstName: 'Dan',
lastName: 'Wahlin'
}
]
};
chrome的错误是: - 未捕获的TypeError:AuthorApi.getAllAuthors不是函数
答案 0 :(得分:3)
您没有导出AuthorApi
功能。尝试添加:
module.exports = AuthorApi
文件末尾的 authorApi.js
。