渲染组件时,我试图获取一个游戏列表并将它们以无序列表的形式打印在页面上。该API调用正常工作,并且Redux Dev Tools显示商店已更新,但该组件未更新以反映更改。
组件
import React from 'react';
import { connect } from 'react-redux'
import {fetchAllGames} from "../actions";
class Games extends React.Component {
componentDidMount() {
this.props.dispatch(fetchAllGames());
}
render() {
const { games } = this.props;
return(
<ul>
{ games.map(game => <li key={game.id} >{game.name}</li>) }
</ul>
)
}
}
const mapStateToProps = state => (
{
games: state.games
}
)
const GamesList = connect(
mapStateToProps
)(Games)
export default GamesList;
操作
import axios from 'axios';
export const fetchGames = (games) => {
return {
type: 'FETCH_GAMES',
games
}
};
export const fetchAllGames = () => {
return (dispatch) => {
return axios.get('/api/games').then(res=> {
dispatch(fetchGames(res.data))
})
.catch(error => {
throw(error);
});
};
};
商店
import {combineReducers, createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import GamesList from '../games-list/reducers';
import UsersList from "../users/reducers";
const rootReducer = combineReducers({
'friends' : UsersList,
'games': GamesList
})
const store = createStore(rootReducer, applyMiddleware(thunk));
console.log(store.getState())
export default store
减速器
const initialState = [
{
id: 0,
name: 'Test Game',
publisher: 'Test Co.'
}
];
const GamesList = (state = initialState, action) => {
switch(action.type){
case 'ADD_GAME':
return [
...state,
{
id: action.id,
name: action.name,
publisher: action.publisher
}
]
case 'DELETE_GAME':
return state.splice(state.indexOf(action.id), 1);
case 'FETCH_GAMES':
return [
...state,
action.games
]
default:
return state
}
}
export default GamesList;
答案 0 :(得分:1)
您需要传播结果:
这样做:
case 'FETCH_GAMES':
return [
...state,
...action.games
]