this.setState仍为false

时间:2017-09-26 17:42:47

标签: javascript reactjs

我有两个组件CardDeckCard

CardDeck

export default class CardDeck extends React.Component {

    constructor(props) {
        super(props);

    }

    addCards(cards, input, cardType) {
        cards.push(<Card cardType="10" cardNum={1} key = {11} pressed = {false} onCardClicked = {this.selectCard.bind(this)}/>);

        }       
    }

    selectCard(card, callback) {
        this.forceUpdate();
        callback();

    }

    render() {
        var cards = [];

        cards.push(<Card cardType="10" cardNum={1} key = {11} pressed = {false} onCardClicked = {this.selectCard.bind(this)}/>);

        return (<div>
            {cards}
        </div>);
    }
}

卡组件

export default class Card extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            "clicked": this.props.pressed
        };
    }

    componentWillReceiveProps(nextProps) {
        this.props = nextProps;
        this.setState({
            clicked: this.props.pressed
        });
    }

    onClick(e) {
        this.props.onCardClicked({
            cardType: this.props.cardType,
            cardNum: this.props.cardNum
        }, () => {
            this.setState((state, props) => {
                var newState =  {
                    "clicked": !(state.clicked)
                };
                return newState;
            });
        });
    }

    render() {
        var clickedButtonStyle = {
            "borderStyle": "inset"
        };

        var normalButtonStyle = {
            "borderStyle": "outset"
        };

        return <span><button style = {this.state.clicked ? clickedButtonStyle : normalButtonStyle} onClick = {this.onClick.bind(this)}><img comment = "The card image gets picked"/></button></span>;
    }
}

我实施的逻辑是,如果点击一张卡,它会显示borderStyle:inset。但在任何时候,只能点击一张卡。如果用户点击第二张卡片,则必须将第一张卡片的borderStyle更改为一开始,并且必须插入第二张卡片的样式。因此,当点击一张卡时,它会调用父CardDeckselectCard)中的函数,该函数会触发所有卡片的重新渲染到pressed=false。然后调用传递给它的回调,这会将按下的卡的this.state.clicked更改为true。

但由于某种原因,来自CardDeck组件的重新渲染与回调状态更新捆绑在一起,并且按下的卡this.state.clicked仍为假。

任何人都可以纠正我,我做错了什么或建议替代方法吗?

0 个答案:

没有答案