【问题标题】:Using withState and lifecycle from recompose together一起使用 withState 和生命周期 from recompose
【发布时间】:2019-02-01 22:33:16
【问题描述】:

我想构建一个组件,将数字道具随机更新到棋盘上的不同位置。

为了做到这一点,我创建了一个带有间隔的简单组件:

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)

【问题讨论】:

  • 能否具体说明您面临的问题
  • 对不起,对我来说,这看起来像是在请别人为你写,你能解释一下你尝试了什么吗? :-)

标签: reactjs recompose


【解决方案1】:

你的小提琴有几个问题。

首先:你还没有从Recompose导入lifecycle

第二:moveKnight 是一个函数,因此需要像这样调用它

 this.interval = setInterval(() => {
         this.props.moveKnight(
             [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]
         );
    }, 500)

Working DEMO

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2021-01-03
    • 2018-10-05
    相关资源
    最近更新 更多