2017-06-12 15 views
0

說,我有我的申請作出反應在我的減速器存在以下狀態如下:顯示事情一個接一個在屏幕上的反應,和/終極版

{ 
array: ["Person 1", "Person 2", "Person 3"]; 
} 

我想要做的就是這個。我希望用戶按空格鍵,屏幕上會顯示Person 1。我希望用戶再次按下空格鍵,並在屏幕上添加Person 1Person 2,依此類推。

我不知道如何做到這一點,我怎麼能在Redux中控制列表中有多少人顯示。

對於這個非常基本的問題,我很抱歉,我對React/Redux相當陌生。我知道如何才能通過陣列,並且一次顯示一個人,或者一次顯示一個人,或者一次顯示一個人的功能map。但我正在努力將它們逐漸添加到視圖中。

回答

2

有很多方法可以做到這一點,這裏有一個:

export class App extends Component { 
    constructor(props){ 
    super(props) 
    this.state = { 
     players: [], 
     currentPlayer: 0 
    } 
    } 
    componentDidMount() { 
    document.addEventListener('keypress', (e) => { 
     if (e.keyCode !== 32) return; 
     this.setState({ currentPlayer: currentPlayer + 1 }) 
     // You should check beforehand if you are in the last index of your array, but I'll not do it here. 
    }); 
    } 
    // You need to remove the event Listener on willUnmount as well 
    render() { 
    if (!this.state.players.length) 
     return <div> No Players </div> 
    return (
     <div>{this.state.players[this.state.currentPlayer]}</div> 
    ) 
    } 

這是一些基本的結構,沒有終極版。您可以稍後添加redux,但我建議您在跳轉到Redux之前學習React的基礎知識。

+0

謝謝!據我瞭解這個代碼,它總是會向我展示**一個**當前玩家。但是,如果我按空格3次,我不想只顯示第3個玩家,而是全部玩家**直到第三個**。 –

+0

是的,我錯過了。您可以輕鬆地重構此代碼,將'currentPlayer'更改爲'currentPlayersIds'或類似的東西,並映射包含在'currentPlayerIds'中的玩家 – BravoZulu

相關問題