【问题标题】:Showing things one by one on screen in React/Redux在 React/Redux 的屏幕上一一显示
【发布时间】:2017-06-12 19:39:23
【问题描述】:

假设我的 React 应用程序中有以下内容,其中我的 reducer 保持以下状态:

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

我想做的就是这个。我希望用户按下空格键并在屏幕上显示Person 1。我希望用户然后再次按空格键,并在屏幕上添加Person 1 Person 2,依此类推。

我不知道该怎么做,我不知道如何在 Redux 中控制要显示列表中的多少人。

对于这个非常基本的问题,我很抱歉,我对 React/Redux 还很陌生。我知道我怎样才能遍历数组并始终一次显示一个人,或者使用map 函数一次显示一个人。但我正在努力将它们逐渐添加到视图中。

【问题讨论】:

    标签: javascript arrays reactjs redux react-redux


    【解决方案1】:

    有很多方法可以做到这一点,这里有一个:

    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,但我建议你在跳到 Redux 之前学习 React 的基础知识

    【讨论】:

    • 谢谢!据我了解这段代码,它总是会向我显示 one 当前播放器。但是,如果我按空格 3 次,我不想只显示第三个玩家,而是所有玩家直到第三个
    • 是的,我错过了。您可以轻松地重构此代码,将currentPlayer 更改为currentPlayersIds 或类似的东西,并映射包含在currentPlayerIds 中的玩家
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多