【发布时间】:2019-09-23 06:25:10
【问题描述】:
当一个组件被渲染时,我试图获取一个游戏列表并将它们以无序列表的形式打印在页面上。 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;
【问题讨论】:
-
你使用过例如Redux 开发工具来找出正在发生的操作以及状态是否正在更新? React 开发工具来查看组件的 props 是什么?控制台中是否有任何消息?你有没有做过其他调试?
-
目前我不确定如何设置 Redux 开发工具。在此过程中,我已经完成了一些控制台日志,因此我知道肯定会获取数据。
-
好的,所以我已经设置了开发工具,并且状态肯定在更新,所以我将编辑我的问题。
-
谢谢@Roy.B - 我需要传播运算符! :)
-
@ChrisWickham 很酷,我写下答案,很高兴我能提供帮助
标签: reactjs redux react-redux