正如我在控制台中看到的那样,我的状态正在改变,但是我的Book组件在状态改变时没有刷新。我的应用程序中有两个容器/组件。 BookList呈现所有可用书籍的列表。 Book组件仅获取activeBook并显示其详细信息。我正面临Book Component的重新提交问题。
import React, {Component} from 'react';
import {connect} from 'react-redux';
class Book extends Component{
render(){
return(
<div className="col-md-9 details">
<h3>Title: {this.props.activeBook.name}</h3>
<p><b>Author:</b> {this.props.activeBook.author}</p>
<p><b>Pages:</b>{this.props.activeBook.pages}</p>
<p><b>Available:</b>{this.props.activeBook.aval}</p>
{console.log(this.props)}
</div>
);
}
}
const mapStateToProps = (state) =>{
return {
activeBook: state.active
}
}
export default connect(mapStateToProps)(Book);
我的BookList组件如下
import React, {Component} from 'react';
import {connect} from 'react-redux';
class BookList extends Component{
renderList(){
return this.props.books.map((book)=>{
return(
<li
key={book.id}
onClick={() => this.props.dispatch({type:'CHANGED',activeBook:book})}
className="list-group-item">
{book.name}
</li>
);
});
}
render(){
return(
<div className="col-md-3">
<ul className='list-group'>
{this.renderList()}
</ul>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
books:state.books
}
}
export default connect(mapStateToProps)(BookList);
我的App.js如下:-
import React, { Component } from 'react';
//Import All Components Here
import BookList from './containers/BookList';
import Book from './components/Book';
class App extends Component {
render() {
return (
<div className="container">
<div className="App">
<div className="row">
<BookList/>
<Book/>
</div>
</div>
</div>
);
}
}
export default App;
最后我的bookReducer如下:-
const bookReducer = (state = [], action) => {
switch(action.type){
case 'CHANGED':
state.active=action.activeBook;
return state;
default:
return state;
}
}
export default bookReducer;
我可以在控制台中确切地看到状态已更改,但是问题是Book Container无法响应该更改。在index.js中,这是我的代码
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import App from './App';
import bookReducer from './reducers/bookReducer';
const initialState={
books:[
{id:1,name:'Learn Java', author:'Shakeel', pages:50,aval:'Yes'},
{id:2,name:'React Native', author:'Asim', pages:212,aval:'No'},
{id:3,name:'Angular JS', author:'Tahir', pages:150,aval:'Yes'},
{id:4,name:'NodeJS', author:'Saleem', pages:120,aval:'Yes'},
{id:5,name:'C++ for Games', author:'Shakeel', pages:140,aval:'Yes'}
],
active:{id:5,name:'C++ for Games', author:'Shakeel', pages:140,aval:'Yes'}
};
const store = createStore(bookReducer,initialState);
ReactDOM.render(<Provider store={store}>
<App /></Provider>,
document.getElementById('root'));
答案 0 :(得分:1)
在reducer中设置状态的方式需要更改,请尝试更改。
const bookReducer = (state = [], action) => {
switch(action.type){
case 'CHANGED':
return {
...state,
active : action.activeBook
}
default:
return state;
}
}