假设我的 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/