E
E
Evgeny Kucherenko2016-12-15 03:32:27
React
Evgeny Kucherenko, 2016-12-15 03:32:27

How to fix status update?

UPD : the problem was, this.state.store.delete(element) didn't return state . Store should be processed first , and only then the new state should be written to setState.
I draw an N x N grid. Imagine that the grid is a similar N x N array. I need to get the index of its element when clicked, which, in turn, will be written to store .
That is, I get the coordinates ( x , y ) relative to the canvas and translate them into the index of the element. Store is an associative array. Recording condition: if there is no element, then I write it down, if there is, then I erase it.
Not only is the index that I need written down as a rule the second time, after erasing the index, the console gives an error TypeError: this.state.store.has is not a function. (In 'this.state.store.has(element)', 'this.state.store.has' is undefined)
How to fix?

export default class SimulationField extends React.Component {
    
    constructor(props) {
        super(props);
        
        this.state = {
            store: new Map(),
            scale: 20,
            edge: this.props.edge,
            element: 0
        }
    }
    
    handleClick(e) {
        
        let x = Math.floor(getMouseX(e, this.refs.canvas) * this.state.scale / this.state.edge)
        let y = Math.floor(getMouseY(e, this.refs.canvas) * this.state.scale / this.state.edge)
        
        let element = xy2Key(this.state.scale)([x, y])
        
        this.setState({ 
            store: ( this.state.store.has(element) )
                        ? this.state.store.delete(element)
                        : this.state.store.set(element, true)
        })
    }
    
    componentDidMount() {
        this.updateCanvas();
    }
    
    updateCanvas() {
        const ctx = this.refs.canvas.getContext('2d');
        renderGrid({ ctx, edge: this.state.edge, scale: this.state.scale })
    }
    
    render() {
        return (
            <div>
                <canvas
                    ref="canvas"
                    width={this.state.edge}
                    height={this.state.edge}
                    onClick={this.handleClick.bind(this)}>
                </canvas>
            </div>
        );
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aves, 2016-12-15
@Aves

Well, do the processing first, and then the installation.

const {store} = this.state;

if (store.has(element)) store.delete(element);
else store.set(element, true);

this.setState({store});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question