Когда компонент отображается, я пытаюсь получить список игр и распечатать их на странице в неупорядоченном списке.Вызов 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;