一起使用 withState 和 recompose 中的生命周期
Using withState and lifecycle from recompose together
我想构建一个组件,将数字道具随机更新到棋盘上的不同位置。
为此,我创建了一个带有间隔的简单组件:
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} />
}
}
我有兴趣使用 withState
和 lifecycle
的重组库将其转换为 Hoc。
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)
您的 fiddle 中有几个问题。
首先:您还没有从 Recompose
导入 lifecycle
其次:moveKnight
是一个函数,因此需要像
一样调用它
this.interval = setInterval(() => {
this.props.moveKnight(
[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
);
}, 500)
我想构建一个组件,将数字道具随机更新到棋盘上的不同位置。
为此,我创建了一个带有间隔的简单组件:
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} />
}
}
我有兴趣使用 withState
和 lifecycle
的重组库将其转换为 Hoc。
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)
您的 fiddle 中有几个问题。
首先:您还没有从 Recompose
lifecycle
其次:moveKnight
是一个函数,因此需要像
this.interval = setInterval(() => {
this.props.moveKnight(
[Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
);
}, 500)