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,想请问下是为什么?找了半天的资料没找到原因。。

阅读 8.6k
1 个回答

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

    test () {
        this.setState({
          checkboxCheck : false
        });
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题