我正在使用react-redux构建一个应用程序,但是我的redux存储存在问题。从Redux devTools中可以看到,当我单击RenderPlayerTransferList
内的元素时,将正确调用操作创建者,并且商店将更新。但是,当尝试访问this.props.currentSquad
(动作创建者更新的状态对象,然后我将其映射到props)时,react组件自身返回未定义。有谁知道为什么会这样吗? (请注意,我正在使用redux thunk)
相关代码:
主要react组件中的代码:
handleTransferPlayerClick=(playerId)=>{
if (this.props.selectedPlayerFromTeamSheet){
this.props.addPlayerToSquad(playerId)
//add new squad into playerIconProps
this.playerIconProps.playerNames[this.props.selectedPlayerFromTeamSheet.iconKey] = this.props.players[this.props.currentSquad.newAdditions]
console.log(this.playerIconProps)
}
}
const mapStateToProps=(state)=>{
return {players:Object.values(state.playerDatabase),
selectedPlayerFromTFLId:state.transfers.TFLPlayerId,
selectedPlayerFromTeamSheet:state.transfers.selectedPlayer,
currentSquad: state.squad
}
}
export default connect(mapStateToProps, {getPlayers, selectPlayerFromTFL, selectPlayerFromTeamSheet, addPlayerToSquad})(Transfers)
动作创建者
export const addPlayerToSquad = (playerId)=>{
return (dispatch, getState) => {
const state = getState().transfers
const payload = {currentSquadMemberId: state.selectedPlayer.iconKey, newSquadAdditionId: playerId}
//recives object with playerId and Iconid t
dispatch({type:ADD_PLAYER_TO_SQUAD, payload:payload})
}
}
减速器
const squadDatabase = {currentSquad: {
0: null,
1: null,
2:null,
3:null,
4:null,
5:null,
6:null,
7:null,
8:null,
9:null,
10:null,
11:null,
12:null,
13:null,
14:null,
15:null
}, newAdditions: null}
export default (state=squadDatabase, action)=>{
switch(action.type){
case ADD_PLAYER_TO_SQUAD:
return {...state, currentSquad: {...state['currentSquad'], [action.payload.currentSquadMemberId]:action.payload.newSquadAdditionId}, newAdditions: action.payload.newSquadAdditionId}
default:
return squadDatabase
}
}
减速器在这里组合...
export default combineReducers ({
// set state object to auth
auth: authReducer,
form: formReducer,
playerDatabase: playerDatabaseReducer,
transfers: transfersReducer,
squad: squadReducer
})
答案 0 :(得分:1)
如果不运行它,您可能需要更改
return squadDatabase
到
return state
否则,看起来该值将始终是硬编码的吗?
然后在mapStateToProps中进行更改
currentSquad: state.squad
到
currentSquad: state.squad.currentSquad