未捕获的类型错误:_this2.props.selectBook不是一个函数。

5

我是ReactJS的新手,正在跟随Udemy上的React基础课程学习。控制台日志中出现了以下错误。有谁能帮忙解决一下吗?

bundle.js:21818 Uncaught TypeError: _this2.props.selectBook is not a function

任何帮助都将不胜感激。谢谢。

容器/书籍列表.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);

actions/index.js

export function selectBook(book) {
    console.log('A book has been selected:', book.title);
}

components/app.js

import React, { Component } from 'react';

import BookList from '../containers/book-list';

export default class App extends Component {
  render() {
    return (
      <div>
        <BookList />
      </div>
    );
  }
}

提供完整的代码。 - kind user
1
发布使用 selectBook 变量的文件。 - kind user
是的,我认为这是为了教程演示目的。无论如何,我已经将该函数添加到book-list.js文件中,但没有运气。 - Cody
这是链接:https://jsfiddle.net/x6ugon6j/ - Cody
似乎它也已经正确链接。*请参见问题描述末尾的文件。 - Cody
显示剩余5条评论
4个回答

8
我找到了答案。
// didnt have included the mapDispatchToProps function call in below lines.
export default connect(mapStateToProps, mapDispatchToProps)(BookList);

1
这就是让我成功的方法,我正在跟随Stephen Grider的Udemy课程。 - Charles Harring

5

请使用 import selectBook from '../actions/index' 代替 import { selectBook } from '../actions/index';


这样做可以使代码更简洁易读。

1

对于已经包含了mapDispatchToProps函数调用的人,即export default connect(mapStateToProps, mapDispatchToProps)(BookList);

浏览actions/index.js并查看是否使用默认导出。 如果没有,则在导入selectBook时需要使用{}

if (using default export) { 

    import selectBook from '../actions/index';
}
else {

    import { selectBook } from '../actions/index';
}

干杯。


0

确保导出 selectBook 动作,以便在应用程序内可用

export function selectBook() {...}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接