React-为什么componentDidMount事件立即被调用

时间:2019-02-27 11:44:06

标签: javascript reactjs setinterval create-react-app

我一直在玩用Mat result, result_mask; blender->blend(result, result_mask); // The result image is in 'result' 实现的动画。 在该应用程序中,我创建了一辆在轨道上行驶的汽车。在这条赛道上,汽车应该识别出障碍物。 我将reactjs用于重复事件。也许这不是最佳选择,但实际上我不知道该怎么办。

由于进行了一些更改,因此运行了多个时间间隔。 但是实际上我不知道原因。有人可以给我一个提示,为什么赛车组件在window.setInterval事件中立即运行?

componentdidmount组件正在向Racer组件提供当前位置和度数/脚踝。 Track组件将这些值存储在Track中,并将其作为states交给Racer组件。但这不应导致立即触发props组件的componentdidmount事件,或者?

这是我的代码:

App.js

Racer

Track.js

import React, { Component } from 'react';
import Track from './components/track.js';
const uuidv1 = require('uuid/v1');

class App extends Component {

  constructor(props) {
    super(props);
    this.state = { 
      obstacles: [
        {
          key: uuidv1(),
          position: {
            left: 500,
            top:10,
          },
          width: 25,
          height: 25,
        },
        {
          key: uuidv1(),
          position: {
            left: 650,
            top:60,
          },
          width: 25,
          height: 25,
        }
      ],
    };
  }

  render() {
    return (
      <div className="App">
        <Track width={800} height={100} obstacles={this.state.obstacles}>
        </Track>
      </div>
    );
  }
}

export default App;

Racer.js

import React, { Component } from 'react';
import styled from 'styled-components';
import Racer from './racer.js';
import Obstacle from './obstacle';
import centralStrip from '../images/centralStrip.png';
const uuidv1 = require('uuid/v1');

class Track extends Component {

    constructor(props) {
        super(props);
        this.state = { 
            racerCurrentPosition: {
                top: 60,
                left:150
            },
            racerDegree: 0,
        };

    }

    componentDidMount() {
    }

    handleObstacleCheck(position, racerPosition) {
        let obstacleFound = false;
        obstacleFound = this.props.obstacles.map((obstacle) => {
            let returnValue = false;
            let obstacleRect = document.getElementById(obstacle.key).getBoundingClientRect();
            if( position.right >= obstacleRect.left && position.right <= obstacleRect.right && racerPosition.top >= obstacleRect.top && racerPosition.bottom <= obstacleRect.bottom) {
                returnValue =  true;
            }
            return returnValue;
        });
        let isObstacleFound = false;
        if(obstacleFound.indexOf(true) !== -1) {
           isObstacleFound = true; 
        }
        return isObstacleFound;
    }

    handleRacerPositionChange(position) {
        this.setState({
            racerCurrentPosition: position,
        });
    }

    handleRacerDegreeChange(newDegree) {
        this.setState({
            racerDegree: newDegree,
        });
    }

    render() {
        return (
            <TrackImage key={uuidv1()} 
                        id="track" 
                        width={this.props.width} 
                        height={this.props.height}>
                <Racer  key={uuidv1()} 
                        position={this.state.racerCurrentPosition} 
                        onRacerPositionChange={this.handleRacerPositionChange.bind(this)} 
                        degree={this.state.racerDegree}
                        onRacerDegreeChange={this.handleRacerDegreeChange.bind(this)}
                        obstacleFound={this.state.obstacleFound} 
                        trackWidth={this.props.width} 
                        trackHeight={this.props.height} 
                        onObstacleCheck={this.handleObstacleCheck.bind(this)} 
                />
                {
                    this.props.obstacles.map((obstacle) => {
                        return (
                            <Obstacle   key={obstacle.key} 
                                        id={obstacle.key} 
                                        position={obstacle.position} 
                                        width={obstacle.width} 
                                        height={obstacle.height} 
                            />
                        );
                    })
                }
            </TrackImage>
        );
    }
}

export default Track;

import React, { Component, Fragment } from 'react'; import styled from 'styled-components'; import HelperDistance from './helpers/distance.js'; import HelperCenterCar from './helpers/centerCar.js'; import racerImage from '../images/racer.png'; const uuidv1 = require('uuid/v1'); class Racer extends Component { constructor(props) { super(props); this.state = { key: uuidv1(), intervalId: 0, speed: 0, helperForLeftPositioning: 0, helperForTopPositioning: 0, isMoving: false, collision: false, centerOfCarCoordinates: { x: 25, y: 12.5 }, obstacleFound: false, }; this.start = this.start.bind(this); this.move = this.move.bind(this); } componentDidMount() { if(this.state.intervalId === 0) { this.start(); } } componentWillUnmount() { window.clearInterval(this.state.intervalId); } start() { this.setState({ speed: 3, isMoving: true, }, () => { this.createInterval(); }); } stop() { this.setState({ speed: 0, isMoving: false, }, () => { window.clearInterval(this.state.intervalId); }); } move() { if(this.state.obstacleFound === true) { let newDegree; if(this.props.degree === 0) { newDegree = 360; } newDegree--; this.props.onRacerDegreeChange(newDegree); } this.step(); } step() { if(this.state.isMoving) { //...calculate new position this.setState({ helperForTopPositioning: helperForTopPositioning, helperForLeftPositioning: helperForLeftPositioning, },() => { let position = { left: positionNewLeft, top: positionNewTop }; this.props.onRacerPositionChange(position); }); } } createInterval = () => { let intervalId = window.setInterval(() => { this.move(); console.log("IntervalId: " + intervalId); },100); this.setState({ intervalId: intervalId, }) } handleDistanceChange(position) { let racerRect = document.getElementById(this.state.key).getBoundingClientRect(); let obstacleFound = this.props.onObstacleCheck(position, racerRect); if(this.state.obstacleFound !== obstacleFound) { this.setState({ obstacleFound: obstacleFound }); } } render() { return ( <Fragment> <Car key={this.state.key} id={this.state.key} position={this.props.position} degree={this.props.degree}> <HelperCenterCar key={uuidv1()} position={this.state.centerOfCarCoordinates} degree={this.props.degree} /> <HelperDistance key={uuidv1()} onChange={this.handleDistanceChange.bind(this)} position={this.state.centerOfCarCoordinates} degree={this.props.degree} /> </Car> </Fragment> ); } } export default Racer; HelperCenterCar是组成部分,有助于识别是否有障碍。我将仅发布HelperDistance的代码,因为在这里会立即触发HelperDistance更新。

HelperDistance.js

state

0 个答案:

没有答案