javascript - 在 React/Redux 中在屏幕上一一显示内容

标签 javascript arrays reactjs redux react-redux

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

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

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

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

我对这个非常基本的问题感到抱歉,我对 React/Redux 还很陌生。我知道如何可以只浏览数组并始终一次显示一个人,或者使用 map 函数一次显示所有内容。但我正在努力考虑将它们逐渐添加到 View 中。

最佳答案

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

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 的基础知识

关于javascript - 在 React/Redux 中在屏幕上一一显示内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44507463/

相关文章:

javascript - 通过 React 从 mongoDB 中检索数据

reactjs - 运行玩笑测试时,覆盖失败并出现意外 token

node.js - 无法为我的静态资源 Express 设置缓存控制 header

Javascript - 如何编写异步函数

javascript - ES6 : How to access a static getter from an instance

python - 将元素插入 numpy 数组的更好方法

C++:错误:获取临时 [-fpermissive] 的地址

javascript - 如何在圆形 Canvas 上添加线条

javascript - jquery 或 javascript 中是否有 isTextSelected() 的替代方法?

Android 数组结果显示在多个 TextView 中