簡體   English   中英

一起使用 withState 和 Lifecycle from 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} />
    }
}

我有興趣使用使用withStatelifecycle的重構庫將其轉換為 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)

你的小提琴有幾個問題。

第一:你還沒有從Recompose導入lifecycle

第二: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM