Counter
组件与0
一起使用。 this 到处都没有,所以抓住了错误吗?
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
setInterval(this.setState, 1000, {
count: this.state.count + 1
})
}
render() {
return <p>{this.state.count}</p>
}
}
答案 0 :(得分:1)
您的setInterval
(和setState
)语法应如下所示:
setInterval(() => {
this.setState(state => ({
count: state.count + 1
}));
}, 1000)
setState
是异步的,因此如果
您将使用对象版本。运行示例:
class Counter extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
setInterval(() => {
this.setState(state => ({
count: state.count + 1
}));
}, 1000)
}
render() {
return <p > {
this.state.count
} < /p>
}
}
ReactDOM.render(<Counter/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />