react.js - React子组件中componentWillReceiveProps不执行

查看:135
本文介绍了react.js - React子组件中componentWillReceiveProps不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

父组件:

class PageCheckbox extends React.Component {
    constructor (props) {
        super(props)
        this.state = {
            checkboxCheck: true
        }
    }

    test () {
        this.state.checkboxCheck = false
        console.log(this.state.checkboxCheck)
    }

    render () {
        return <section className="checkbox-wrapper">
                    <Checkbox checked={ this.state.checkboxCheck }>checkbox</Checkbox>
                    <Button clickHandler={ this.test.bind(this) }>test</Button>
                </section>
    }
}

子组件

    class Checkbox extends Component {
    constructor (props) {
        super(props)
        this.state = {
            checked: props.checked
        }
    }

    componentWillReceiveProps (nextProps) {
        console.log('received', nextProps)
        this.setState({
            checked: nextProps.checked
        })
    }

    render () {
        return <label className={ `${ this.getLibName() }-checkbox` }>
                    <span className={ `${ this.getLibName() }-checkbox__input` }>
                        <span className={ this.formatClsNames(
                                `${ this.getLibName() }-checkbox__selector`,
                                this.state.checked ? `${ this.getLibName() }-checked` : '',
                                this.props.disabled ? `${ this.getLibName() }-disabled` : ''
                            ) }></span>
                        <input type="checkbox"
                                checked={ this.state.checked }
                                className={ `${ this.getLibName() }-origin-el` }
                                onChange={ this.onChange.bind(this) }/>
                    </span>
                    <span className={ `${ this.getLibName() }-checkbox__label` }>
                        { this.props.children }
                    </span>
                </label>
    }
}

Checkbox.propTypes = {
    checked: PropTypes.bool
}

Checkbox.defaultProps = {
    checked: false
}

在父组件中点了按钮之后,并没有调用子组件中的componentWillReceiveProps,想请问下是为什么?找了半天的资料没找到原因。。

解决方案

React改变组件状态要通过调用setState的方式,不能直接改变state的值,你父组件中test方法应该改为:

    test () {
        this.setState({
          checkboxCheck : false
        });
    }

这篇关于react.js - React子组件中componentWillReceiveProps不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆