我在Stackoverflow社区遇到过类似的问题,但问题的答案并没有解决我的困境。在互联网上尝试几乎所有与此问题相关的内容之后,我一直遇到这个问题。所以请回答这个问题,以便在我的开发中取得进展。非常感谢任何帮助。
图书-list.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index.js';
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
const 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 ot available
//as a prop.
export default connect(mapStateToProps, mapDispatchToProps)(BookList);
index.js - 减少者
import { combineReducers } from 'redux';
import BooksReducer from './reducer_books';
const rootReducer = combineReducers({
books: BooksReducer
});
export default rootReducer;
index.js - 操作
function selectBook(book) {
console.log('A book has been selected', book.title);
}