我对Redux和Reducer都很陌生。我不能让我的第一个代码工作。任何人都可以告诉我为什么(index.js)引用BooksReducer?我没有这样的道具,组件或文件。它会抛出这样的错误: "未捕捉的错误:Reducer" books"在初始化期间返回undefined。如果传递给reducer的状态未定义,则必须显式返回初始状态。"我该如何初始化它?
reducer_book.js:
export default function(){
return
[
{title: 'Crash bandicoot'},
{title: 'Crash bandicoot 2: Cortex strikes back'},
{title: 'Crash bandicoot 3: Warped'},
{title: 'Crash Team Racing'},
{title: 'Crash Bash'}
]
}
index.js:
const rootReducer = combineReducers({
books: BooksReducer
});
export default rootReducer;
App.js:
export default class App extends Component {
render() {
return (
<div>
<BookList />
</div>
);
}
}
book_list.js:
class BookList extends Component{
renderList(){
return this.props.books.map((book) => {
return(
<li key={book.title} className="list-group-item">{book.title}</li>
);
});
}
render(){
return(
<ul className="list-group col-sm-4">
{this.renderList()}
</ul>
)
}
}
function mapStateToProps(state){
return {
books: state.books
};
}
export default connect(mapStateToProps)(BookList);
答案 0 :(得分:2)
看起来就像你在reducer中的return
语句之后有一个换行符一样,这可能会导致Javascript将其解释为return;
,而不是比return [ ];
。尝试将阵列的左括号移至与return
关键字相同的行。