Come cambiare il colore di elementi specifici nell'array

Aug 21 2020

Sto cercando di creare un visualizzatore di ordinamento usando React. In questo momento, sto implementando BubbleSort. Il programma si presenta così:

Ecco il codice:

class Sorter extends Component {

    state = {
        array: [100,4,214,55,11,22,10,33],
        color: "blueviolet",
    } 

    bubblesorter = async () => {
        let arr = this.state.array
        var len = arr.length,
        i, j, stop;
            for (i=0; i < len; i++){
                    for (j=0, stop=len-i; j < stop; j++){
                        if (arr[j] > arr[j+1]){
                            swap(arr, j, j+1);
                        } 
                        await new Promise(resolve => setTimeout(resolve, 100));
                        this.setState({array:arr})
                    }
                }   
    }

    render() {
        const array = this.state.array
        return (
            <div>
                <h1>This is a sorter</h1>
                <div className="container">
                    {array.map((value, id) => (
                        <span>
                            <div className="bar" key={id} style={{height: value+"px", backgroundColor: this.state.color}}  >
                            </div>
                        </span>
                    ))}
                </div>
                <button onClick={this.bubblesorter}>Sort</button>
            </div>
        )
    }

La funzionalità di ordinamento funziona correttamente. Ma vorrei cambiare il colore delle barre (elementi dell'array confrontati). Qualcuno può aiutare con la logica che può essere utilizzata per implementare questo ... Grazie

Risposte

1 yash Aug 21 2020 at 15:05

Puoi creare la colorsmatrice e aggiornare il colore che è stato solo cambiato.

class Sorter extends Component {
    state = {
        array: [100, 4, 214, 55, 11, 22, 10, 33],
        colors: Array(8).fill('blueviolet'),  // Array of colors for each bar
    };

    bubblesorter = async () => {
        ...
                await new Promise((resolve) => setTimeout(resolve, 100));
                
                // Set different item's color as `red`
                const colors = arr.map((item, index) => (this.state.array[index] === item ? 'blueviolet' : 'red'));
                this.setState({ array: arr, colors });
            }
        }
    };

    render() {
        const { array, colors } = this.state;
        return (
            <div>
                <h1>This is a sorter</h1>
                <div className='container'>
                    {array.map((value, id) => (
                        <span>
                            <div
                                className='bar'
                                key={id}
                                // <- Use the color at the same index of the item
                                style={{ height: value + 'px', backgroundColor: colors[id] }}
                            ></div>
                        </span>
                    ))}
                </div>
                <button onClick={this.bubblesorter}>Sort</button>
            </div>
        );
    }
}

Dev5 Aug 21 2020 at 17:53

Ho provato questo ... funziona ma può essere migliorato utilizzando javascript moderno (non molto familiare, suggerimenti benvenuti)

class Sorter extends Component {

    state = {
        array: [],
        colors: Array(8).fill('blueviolet'),
    } 
    bubblesorter = async () => {
    ...
                        await new Promise(resolve => setTimeout(resolve, 1000));
                        const colors = []
                        for (let k=0; k<8; k++) {
                            let color = k==j || k==j+1 ? 'red':'blueviolet'
                            colors[k] = color
                        }
                        // console.log(colors)
                        this.setState({ array: arr, colors: colors });
             
              }
      }
      render() 
      {
        // const array = this.state.array
        const { array, colors } = this.state;
        // console.log(array)
        return (
            <div>
                <h1>This is a sorter</h1>
                <div className="container">
                    {array.map((value, id) => (
                        <span>
                            <div 
                                className="bar" 
                                key={id} 
                                style={{ height: value + 'px', backgroundColor: colors[id] 
                             }} >
                            </div>
                            {/* <span>{value}</span> */}
                        </span>
                    ))}
                </div>
                <button onClick={this.bubblesorter}>Sort</button>
            </div>
        )
    }
}