[英]Using withState and lifecycle from recompose together
I would like to build a component that randomly updates numeric props to different positions on a chessboard.我想构建一个组件,将数字道具随机更新到棋盘上的不同位置。
In order to do this, I created a simple component with an interval:为了做到这一点,我创建了一个带有间隔的简单组件:
JSFIDDLE: https://jsfiddle.net/ezxnjc8h/ JSFIDDLE: https ://jsfiddle.net/ezxnjc8h/
export default class RandomPosition extends React.Component {
constructor(props) {
super(props)
this.interval = null;
this.state = {
x: 0,
y: 0
}
}
componentDidMount() {
this.interval = setInterval(() => {
this.setState({
x: Math.floor(Math.random() * 8),
y: Math.floor(Math.random() * 8)
})
}, 500)
}
componentWillUnmount() {
clearInterval(this.interval)
}
render() {
return <Test knightPosition={[this.state.x, this.state.y]} moveKnight={this.props.moveKnight} />
}
}
I am interested in converting the same to a Hoc using the recompose library using withState
and lifecycle
to do so.我有兴趣使用使用
withState
和lifecycle
的重构库将其转换为 Hoc 来这样做。
JSFIDDLE: https://jsfiddle.net/kzwc9yha/ JSFIDDLE: https ://jsfiddle.net/kzwc9yha/
export default compose(
withState('knightPosition', 'moveKnight', [1,7]),
lifecycle({
componentDidMount() {
this.interval = setInterval(() => {
this.props.moveKnight[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
}, 500)
},
componentWillUnmount() {
clearInterval(this.interval)
}
})
)(Test)
There are a couple of issues in your fiddle.你的小提琴有几个问题。
First: You haven't imported lifecycle
from Recompose
第一:你还没有从
Recompose
导入lifecycle
Second: moveKnight
is a function and hence it needs to be invoked like第二:
moveKnight
是一个函数,因此需要像这样调用它
this.interval = setInterval(() => {
this.props.moveKnight(
[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
);
}, 500)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.