我的 redux reducer 有问题,在分派(dispatch) FETCH_BOOKS 操作后它不会返回预期状态,它返回一个空对象而不是由 AJAX 请求获取的书籍状态对象, 当将我的状态存储在数组而不是对象中时, reducer 返回正确的数据,这太令人困惑了,为什么会发生这种情况?
这些是我的组件
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import * as BooksAPI from './BooksAPI';
import registerServiceWorker from './registerServiceWorker';
import { createStore, applyMiddleware } from 'redux';
import { bookReducer } from './reducers/BookReducer';
import thunk from 'redux-thunk';
import {BrowserRouter as Router} from 'react-router-dom';
const middleware = [thunk];
const initialState = {};
const store = createStore(bookReducer, initialState, applyMiddleware(...middleware));
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import { connect } from 'react-redux'
import BookShelf from './components/BookShelf'
import AllShelves from './components/AllShelves'
import Header from './components/Header';
import SearchPage from './components/SearchPage';
import * as BooksAPI from './BooksAPI';
import { Route, withRouter } from 'react-router-dom';
import './App.css';
class App extends Component {
componentWillMount() {
this.props.fetchBooks();
}
render() {
console.log(this.props.books)
return (
<div className="App">
<Header />
<Route exact path="/" component={AllShelves} />
<Route path="/search" component={SearchPage} />
</div>
);
}
}
const mapStateToProps = (state) => {
return {
books: state.books
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchBooks: () => {
BooksAPI.getAll().then(books => dispatch({
type: 'FETCH_BOOKS',
books
}))
},
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
reducer 不起作用
import { FETCH_BOOKS } from '../actions/Types.js';
import * as BooksAPI from '../BooksAPI'
const initialState = {
books: [],
query: ''
}
export const bookReducer = (state = initialState, action) => {
switch(action.type) {
case 'FETCH_BOOKS':
return {
...state,
books: action.books,
}
default:
return state;
}
}
有效的 reducer
export const bookReducer = (state = [], action) => {
switch(action.type) {
case 'FETCH_BOOKS':
return action.books
default:
return state;
}
}
那么为什么在对象中存储状态不起作用并且它与数组完美配合,我不想将我的状态存储在数组中,因为书籍不是我需要在状态中管理的唯一数据!!!
最佳答案
我检查了您的所有代码,我认为问题可能来自 redux 存储设置:
const initialState = {};
const store = createStore(bookReducer, initialState, applyMiddleware(...middleware));
我建议删除初始状态:
const initialState = {}; // remove this line cuz we don't need it
const store = createStore(bookReducer, applyMiddleware(...middleware)); //fixed like this
此外,我认为您应该在 componentDidMount()
生命周期 Hook 中获取书籍,而不是 componentWillMount()
,如下所示:
componentDidMount() {
this.props.fetchBooks();
}
关于javascript - 为什么从我的 reducer 返回的状态是一个空对象??(React-Redux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52685014/