你好,我正在尝试让化简器“ removePlayer”更新其生成的状态,使其selectedPlayerIndex为-1,但我似乎无法使其正常工作,我一直在寻找类似的问题,但是无法找到足以提供信息的答案。
这是代码
Flush
这是顶层组件
import * as PlayerActionTypes from '../actiontypes/player';
const initialState = {
players: [{
name: 'Jim Hoskins',
score: 31,
created: '11/8/2016',
updated: '11/9/2016'
},
{
name: 'Andrew Chalkley',
score: 20,
created: '11/9/2016',
updated: '11/10/2016'
},
{
name: 'Alena Holligan',
score: 50,
created: '11/11/2016',
updated: '11/12/2016'
}
],
selectedPlayerIndex: -1
}
export default function Player(state=initialState, action) {
switch(action.type) {
case PlayerActionTypes.REMOVE_PLAYER:
const removePlayerList = [
...state.players.slice(0, action.index),
...state.players.slice(action.index + 1)
];
return {
...state,
players: removePlayerList,
selectedPlayerIndex: -1
}
case PlayerActionTypes.SELECT_PLAYER:
return {
...state,
selectedPlayerIndex: action.index
}
default:
return state;
}
}
这是派遣remove_player的子组件的组件
class Scoreboard extends Component {
static propTypes = {
players: PropTypes.array.isRequired,
selectedPlayerIndex: PropTypes.number.isRequired
};
render() {
const { dispatch, players, selectedPlayerIndex } = this.props;
const addPlayer = bindActionCreators(PlayerActionCreators.addPlayer, dispatch);
const removePlayer = bindActionCreators(PlayerActionCreators.removePlayer, dispatch);
const updatePlayerScore = bindActionCreators(PlayerActionCreators.updatePlayerScore, dispatch);
const selectPlayer = bindActionCreators(PlayerActionCreators.selectPlayer, dispatch)
const playerComponents = players.map((player, index) => (
<Player
index={index}
name={player.name}
score={player.score}
key={player.name}
updatePlayerScore={updatePlayerScore}
removePlayer={removePlayer}
selectPlayer={selectPlayer}
/>
));
return (
<div className="scoreboard">
<Header players={players} />
<div className="players">
{ playerComponents }
</div>
<AddPlayerForm addPlayer={addPlayer} />
<div className="player-detail">
<PlayerDetail players={players} selectedPlayerIndex={selectedPlayerIndex} />
</div>
</div>
);
}
}
const mapStateToProps = state => (
{
players: state.players,
selectedPlayerIndex: state.selectedPlayerIndex
}
);
export default connect(mapStateToProps)(Scoreboard);
如果您需要查看应用程序的其他部分,请告诉我,我试图将代码仅保留我认为必要的内容。
答案 0 :(得分:0)
您似乎有一个嵌套的onClick事件。当您单击removePlayer时,它会传播到selectPlayer。这是由于事件冒泡。您需要阻止事件传播到selectPlayer组件。
event.stopPropagation();
您需要将removePlayer onClick函数更改为以下内容:
function(event) {
props.removePlayer(props.index);
event.stopPropagation();
}
有关事件冒泡和捕获的更多信息,请参见here