我是reactjs的新手,并且正在关注udemy的基础课程。 我在控制台日志中收到以下错误。任何人都可以帮我吗?。
bundle.js:21818 Uncaught TypeError: _this2.props.selectBook is not a function
任何帮助将不胜感激。感谢。
容器/书list.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { bindActionCreators } from 'redux';
class BookList extends Component {
renderList() {
return this.props.books.map((book) => {
return (
<li
key={book.title}
onClick={() => this.props.selectBook(book)}
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
};
}
//Anythin returned from this function will end up as props
// on the BookList container
function mapDispatchToProps(dispatch) {
// whenever selectBook is called, the result should be passed
// to all of our reducers
return bindActionCreators({ selectBook: selectBook }, dispatch);
}
// Promote BookList from a component to a container - it needs to know
// about this new dispatch method, selectBook. Make it available
// as a prop.
export default connect(mapStateToProps)(BookList);
操作/ index.js
export function selectBook(book) {
console.log('A book has been selected:', book.title);
}
组件/ app.js
import React, { Component } from 'react';
import BookList from '../containers/book-list';
export default class App extends Component {
render() {
return (
<div>
<BookList />
</div>
);
}
}
答案 0 :(得分:8)
自己找到答案。
// didnt have included the mapDispatchToProps function call in below lines.
export default connect(mapStateToProps, mapDispatchToProps)(BookList);
答案 1 :(得分:5)
使用import selectBook from '../actions/index'
代替import { selectBook } from '../actions/index';
答案 2 :(得分:0)
确保导出selectBook操作,以便它可以在应用程序中使用
export function selectBook() {...}
答案 3 :(得分:0)
对于已经包含mapDispatchToProps
函数调用的人,即export default connect(mapStateToProps, mapDispatchToProps)(BookList);
浏览action / index.js,查看是否使用默认导出。
如果不是,则在导入selectBook时需要{}
左右。
if (using default export) {
import selectBook from '../actions/index';
}
else {
import { selectBook } from '../actions/index';
}
干杯。