我有一个状态为users
的对象,我想对其进行迭代并每x
秒显示一个不同的用户。
这是我到目前为止所拥有的:
class DisplayUser extends Component { constructor(props) {
super(props);
this.state = {
users: [
{ name: 'batman', age: 25 },
{ name: 'spiderman', age: 27 },
{ name: 'superman', age: 26 }
]
};
}
tick() {
this.setState((prevState) => ({
users: prevState.users
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return <div>User: {this.state.users[0].name}</div>;
}
}
本质上是一个for
循环,但是我发现很难做到反应,我该怎么做?
答案 0 :(得分:2)
当前版本存在两个问题:
setState
调用不会执行任何操作,因为您实际上并未更改状态
您始终在users
中显示第一个条目,而不更改它
我将状态存储在索引中,然后在render
中使用该索引,并用***
注释标记更改:
class DisplayUser extends Component {
constructor(props) {
super(props);
this.state = {
users: [
{ name: 'batman', age: 25 },
{ name: 'spiderman', age: 27 },
{ name: 'superman', age: 26 }
],
currentUserIndex: 0 // ***
};
}
tick() {
this.setState(({users, currentUserIndex}) => ({ // ***
currentUserIndex: (currentUserIndex + 1) % users.length // ***
})); // ***
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
const user = this.state.users[this.state.currentUserIndex];
return <div>User: {user.name}</div>; // ***
}
}
实时示例:
const {Component} = React;
class DisplayUser extends Component {
constructor(props) {
super(props);
this.state = {
users: [
{ name: 'batman', age: 25 },
{ name: 'spiderman', age: 27 },
{ name: 'superman', age: 26 }
],
currentUserIndex: 0 // ***
};
}
tick() {
this.setState(({users, currentUserIndex}) => ({ // ***
currentUserIndex: (currentUserIndex + 1) % users.length // ***
})); // ***
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
const user = this.state.users[this.state.currentUserIndex];
return <div>User: {user.name}</div>; // ***
}
}
ReactDOM.render(<DisplayUser />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>