'componentDidMount'生命周期方法不会更新状态

时间:2020-02-17 21:16:10

标签: javascript reactjs components state render

我有一个名为DiscardPile的组件,可以在您的道具(props.cards)中接收像这样的对象数组:

{key: 'key', 'type', suit: 'suit', label: 'label', flipped: 'fliped, draggable: 'draggable', currentOrder: 0}

好吧,下面显示了组件DiscardPile:

import React, { Component } from 'react';
import $ from 'jquery';
import 'jquery-ui/ui/core';
import 'jquery-ui/ui/widgets/droppable';

import './DiscardPile.scss';

import Card from '../Card/Card';
export default class DiscardPile extends Component {

    constructor(props) {
        super(props);
        this.state = {
            currentCards: []        
        }
    }

    componentDidMount() {
        let currentCards = [...this.props.cards];
        for(let i = 0; i < currentCards.length; i++) {
            currentCards[i].currentOrder = i;
        }
        this.setState({currentCards: currentCards});
    }

    render() {
        return (
            <div id="discard-pile" className="discard-pile">
                {this.state.currentCards.map(card =>(
                    <Card key={card.key} type={card.type} suit={card.suit} label={card.label} flipped={card.flipped} draggable={card.draggable} currentOrder={card.currentOrder}></Card>
                ))}
            </div>
        )
    }

}

'componentDidMount'应该更新对象的currentOrder属性并再次呈现卡列表,但这没有发生。实际上,该列表已变为空。 我该怎么做才能解决此问题?

(对不起,我的英语不好)

-更新-

DiscardPile组件由KlondikeTable组件调用,如下所示:

import React, { Component } from 'react';

import './KlondikeTable.scss';

import Card from './../../generalComponents/Card/Card';
import DiscardPile from '../../generalComponents/DiscardPile/DiscardPile';
import FlippedPile from '../../generalComponents/FlippedPile/FlippedPile';
import SuitsPile from '../../generalComponents/SuitsPile/SuitsPile';
import CardsColumn from '../../generalComponents/CardsColumn/CardsColumn';

export default class KlondikeTable extends Component {

    constructor(props) {
        super(props);
        this.state = {
            cards: [],
            initialDistribution: {
                discardPile: [],
                flippedPile: [],
                cardsPile1: [],
                cardsPile2: [],
                cardsPile3: [],
                cardsPile4: [],
                cardsPile5: [],
                cardsPile6: [],
                cardsPile7: [],
            },
            currentDistribution: null
        }
        this.generateCards = this.generateCards.bind(this);
        this.shuffleCards = this.shuffleCards.bind(this);
    }

    componentDidMount() {
        this.generateCards();
    }

    generateCards() {
        let cards = [];
        let types = ["K","Q","J","10","9","8","7","6","5","4","3","2","A"];
        let suits = ["spades", "clubs", "diamonds", "hearts"];
        for(let i = 0; i < suits.length; i++) {
            for(let j = 0; j < types.length; j++) {
                cards.push(
                    {key: types[j] + "-" + suits[i] + "-0", type: types[j], suit: suits[i], label: "0", flipped: false, draggable: true, currentOrder: 0}
                )
            }
        }
        this.setState(state => ({...state, cards: cards}), () => {
            this.shuffleCards();
        });
    }

    shuffleCards() {
        let amount = 52;
        let numbersArray = [];
        let cards = [...this.state.cards];
        let initialDistribution = {...this.state.initialDistribution};
        for(let i = 0; i < 52; i++) {
            numbersArray.push(i);
        }
        for(let i = 0; i < 24; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            initialDistribution.discardPile.push(removedElement);
            amount--;
        }
        for(let i = 0; i < 28; i++) {
            let randomNumber = Math.floor(Math.random() * amount);
            let removedElement = cards.splice(randomNumber, 1)[0];
            if(i < 1) {
                initialDistribution.cardsPile1.push(removedElement);
            }else if(i < 3) {
                initialDistribution.cardsPile2.push(removedElement);
            }else if(i < 6) {
                initialDistribution.cardsPile3.push(removedElement);
            }else if(i < 10) {
                initialDistribution.cardsPile4.push(removedElement);
            }else if(i < 15) {
                initialDistribution.cardsPile5.push(removedElement);
            }else if(i < 21) {
                initialDistribution.cardsPile6.push(removedElement);
            }else if(i >= 21) {
                initialDistribution.cardsPile7.push(removedElement);
            }
            amount--;
        }
        this.setState({initialDistribution: initialDistribution, currentDistribution: initialDistribution});
    }

    render() {
        return (
            <div className="klondike-table">
                <DiscardPile cards={this.state.initialDistribution.discardPile}></DiscardPile>
                <FlippedPile cards={this.state.initialDistribution.flippedPile}></FlippedPile>
                <div className="suits-piles-container">
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                    <SuitsPile></SuitsPile>
                </div>
                <CardsColumn cards={this.state.initialDistribution.cardsPile1}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile2}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile3}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile4}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile5}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile6}></CardsColumn>
                <CardsColumn cards={this.state.initialDistribution.cardsPile7}></CardsColumn>                
            </div>
        )
    }

}

2 个答案:

答案 0 :(得分:1)

首先,您不需要具有currentCards状态元素。如果您需要始终使用props元素内容更新state元素,则可以这样考虑,您可能会认为这是错误的。而且,如果您的state元素只是在props中接收的元素的微小变化,那么您绝对不需要它。 您的代码无法正常工作,因为在第一个渲染中,您的组件接收到一个空数组,因此设置了一个空的currentCards数组,并且从未对其进行更改。

只需使用

render() {
    return (
        <div id="discard-pile" className="discard-pile">
            {this.props.cards.map((card, currentOrder)=>(
                <Card key={card.key} type={card.type} suit={card.suit} label={card.label} flipped={card.flipped} draggable={card.draggable} currentOrder={currentOrder}></Card>
            ))}
        </div>
    )
}` 

实现预期的行为。

如果您要在状态上仅显示props.cards的初始版本,则可能要使用componentDidUpdate甚至应该使用具有明确定义的规则的componentUpdate来避免性能损失或无限次重新渲染。

答案 1 :(得分:0)

由于componentDidMount仅运行一次,因此如果prop以后进行更改,则您所做的任何更改都不会生效。

道具cards最初设置为[]。因此,除非将排序逻辑移到其他位置,否则它将永远不会以包含已更新数组的状态进行更新。

在不知道所需的确切逻辑的情况下,可能会发生以下情况:

componentDidUpdate(prevProps) {
  if (prevProps.cards.length !== this.props.cards.length) {
    let currentCards = [...this.props.cards];
    for(let i = 0; i < currentCards.length; i++) {
      currentCards[i].currentOrder = i;
    }
    this.setState({currentCards: currentCards});
  }
}

仅当cards数组的长度改变时,这将更新状态。