繁体   English   中英

当父项的状态必须由子项更新时,this.setState不起作用

[英]this.setState not working when a parent's state has to be updated by a child

所以我的应用程序中有一个父组件和一个子组件。 我想通过子组件更新父组件的状态,但它似乎不起作用。 我已经在Reactjs工作了很长时间,这对我来说很奇怪。 这是我的父组件的代码:

import React from 'react';
import { Stage } from 'react-konva';
import CircleComponent from './CircleComponent';
import LineComponent from './LineComponent';
import { getUserPlan } from '../../assets/UserPlan';
import { addColorClasses } from '../../helpers/utils';

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
  }

  getCirclePoints(points) {
    this.setState({
      circlePoints: points,
      word: 'hello'
    }, () => { console.log(this.state); });
  }

  processData() {
    let data = this.state.data;

    if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
      for(let i = 0; i < data.length; i++) {
        data[i].weight /= 3;
      }
    }

    return data;
  }

  render() {
    const processedData = this.processData();
    const firstCircle = processedData.splice(0,1);
    const pmData = processedData.splice(0,this.state.data.length);

    return(
      <div>
        <Stage
          height={800}
          width={1200}
          style={{ backgroundColor: '#fff'}}>
          <CircleComponent
            x={1200/2}
            y={800/2}
            outerRadius={firstCircle[0].weight*1200}
            outerColor={firstCircle[0].outerColor}
            innerRadius={firstCircle[0].weight*1200*0.3}
            innerColor={firstCircle[0].innerColor}
            shadowColor={firstCircle[0].innerColor}
            getCirclePoints={this.getCirclePoints}
          />
        </Stage>
      </div>
    );
  }
}

export default PortfolioMix;

这是子组件的代码:

class CircleComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      points: this.getPoints(),
    };
  }

  componentDidMount() {
    this.props.getCirclePoints(this.state.points);
  }

  getPoints() {
    const radius = this.props.outerRadius;
    const x = this.props.x;
    const y = this.props.y;

    const points = [];
    let angle = 0;

    for(let i = 0; i < 8; i++) {
      points.push({
        pointX: x + radius * Math.cos(-angle * Math.PI / 180),
        pointY: y + radius * Math.sin(-angle * Math.PI / 180)
      });
      angle += 42.5;
    }

    return points;
  }

  render() {
    const {
      x,
      y,
      outerRadius,
      outerColor,
      shadowColor,
      innerRadius,
      innerColor
    } = this.props;

    return (
      <Layer>
        <Group>
          <Circle
            x={x}
            y={y}
            radius={outerRadius}
            fill={outerColor}
            shadowBlur={5}
            shadowColor={shadowColor}
          />
          <Circle
            x={x}
            y={y}
            radius={innerRadius}
            fill={innerColor}
          />
        </Group>
      </Layer>
    );
  }
}

CircleComponent.propTypes = {
  x: propTypes.number.isRequired,
  y: propTypes.number.isRequired,
  outerRadius: propTypes.number.isRequired,
  outerColor: propTypes.string.isRequired,
  shadowColor: propTypes.string,
  innerRadius: propTypes.number.isRequired,
  innerColor: propTypes.string.isRequired,
  getCirclePoints: propTypes.func
};

export default CircleComponent;

现在,在父组件的getCirclePoints方法中,我从子this.setState获取点但是this.setState不起作用。 正如您所看到的,我还将一个函数传递给this.setState回调,它没有被调用,也没有将data状态设置为空数组。 我最近4个小时一直在敲打这个问题。 任何形式的帮助表示赞赏。 我希望我身上没有一些愚蠢的错误。

在React文档中,您可以读到不应该直接修改状态,而只能使用setState()方法修改状态。 您确实直接修改了PorfolioMix状态两次:

  1. processData

     data[i].weight /= 3; 
  2. render

     const processedData = this.processData(); const firstCircle = processedData.splice(0,1); const pmData = processedData.splice(0,this.state.data.length); 

因为代码中的render方法至少被调用两次, this.state.data将是一个空数组,这会导致错误。

你可以在这里看到一个带有错误的实例: https//jsfiddle.net/rhapLetv/

要修复它,您可以在processData方法中返回数据的副本:

processData() {
  const data = this.state.data;

  if(data[0].weight > 0.25 || (data[0].weight+data[1].weight) > 0.67) {
    return data.map(point => ({ ...point, weight: point.weight / 3 }))
  } else {
    return data.slice()
  }
}

带修复程序的实例: https//jsfiddle.net/rhapLetv/1/

您可以找到引入不可变数据的有用的immutable.js (或类似的库/帮助程序)。

你需要在方法processData() .bind(this) ,因为React只会自动绑定(this)来渲染方法,构造函数和组件生命周期方法。

class PortfolioMix extends React.Component {
  constructor(props) {
    super(props);

    const data = addColorClasses(getUserPlan().plans[0]);

    this.state = {
      data: data,
      circlePoints: []
    };

    this.getCirclePoints = this.getCirclePoints.bind(this);
    this.processData = this.processData.bind(this);
  }
// ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM