无法使用setState()更改状态值

时间:2020-07-13 12:11:25

标签: javascript reactjs

我正在尝试使用props从表单组件中获取值,并将其放入我的状态所在的主App组件中。使用我从道具获得的值,我想更新主要状态。这是我的代码:

class App扩展了组件{ 状态= { 数据集:“”, 抄送:“”, cw:0, ch:0, bw:0, bh:0, xspacing:0, yspacing:0, barcolor:“”, };

    .process(exchange -> {
        String strMessage = FileUtils.readFileToString(
                new File(yourFileName), StandardCharsets.UTF_8);
        exchange.getMessage().setBody(strMessage);
        exchange.getMessage().setHeader(Exchange.FILE_NAME, yourFileName);
    })

我正在尝试使用道具将更新后的状态发送到DataGraph组件,但是它不起作用,这是下面的DataGraph组件代码:

  // Function to use the data got from form component and setState
  dataForm = (
    dataset,
    canvascolor,
    canvaswidth,
    canvasheight,
    barwidth,
    barheight,
    xspacing,
    yspacing,
    barcolor
  ) => {
    this.setState({
      dataset,
      canvascolor,
      canvaswidth,
      canvasheight,
      barwidth,
      barheight,
      xspacing,
      yspacing,
      barcolor,
    });
    console.log(this.state);
  };

  render() {
    return (
      <div className="App">
        {/* This is the Form Component from where i'm getting my Data */}
        <DataForm dataForm={this.dataForm} />

        <DataGraph graph={this.state} />
      </div>
    );
  }
}

class DataGraph extends Component { constructor(props) { super(props); this.myRef = React.createRef(); } drawChart() { const d = this.props.graph.dataset.split`,`.map((x) => +x); const accessToRef = d3 .select(this.myRef.current) .append("svg") .attr("width", this.props.graph.cw) .attr("height", this.props.graph.ch) .style("background-color", this.props.graph.cc); accessToRef .selectAll("rect") .data(d) .enter() .append("rect") .attr("x", (d, i) => i * this.props.graph.xspacing) .attr("y", (d, i) => this.props.graph.ch - this.props.graph.yspacing * d) .attr("width", this.props.graph.bw) .attr("height", (d, i) => d * this.props.graph.bh) .attr("fill", this.props.graph.barcolor); } componentDidMount() { this.drawChart(); } render() { return ( <> <div style={{ display: "flex", justifyContent: "center", alignItems: "center", }} ref={this.myRef} className="pb-5" ></div> </> ); } } DataGraph.propTypes = { graph: PropTypes.object.isRequired, }; 未设置状态值。请帮忙。

3 个答案:

答案 0 :(得分:1)

状态正在改变,问题在于setState是一个异步任务,因此您必须等到其结束并验证状态是否正在更新时,请尝试以下代码:-

dataForm = (
dataset,
canvascolor,
canvaswidth,
canvasheight,
barwidth,
barheight,
xspacing,
yspacing,
barcolor
) => {
this.setState({
  dataset,
  canvascolor,
  canvaswidth,
  canvasheight,
  barwidth,
  barheight,
  xspacing,
  yspacing,
  barcolor,
},()=>{
  console.log(this.state);
});

};

setState在完成任务后返回回调,您可以使用它来同步setState函数

当父组件的状态更改时,要更新子组件中的数据,您必须使用以下示例中的道具

const ExampleComponent =(props) =>{
  return <div>
             <Text>{{props.text}}</Text>
         </div>
}

并将道具传递到这样的组件中

<ExampleComponent text={this.state.text} />

现在,每当您更改状态下的文本值时,它将反映在您的子组件中。

答案 1 :(得分:0)

未重新加载组件的主要问题是由于您在组件自身安装时使用了道具,并且在更新状态时它不反映在子组件中

要解决此问题,您必须使用称为 componentWillReceiveProps

的React生命周期挂钩

像这样

  componentWillReceiveProps() {
    this.drawChart();
  }

您还必须在组件中添加此生命周期挂钩,以便每当您的道具更新时,它都会调用该函数并反映更改

答案 2 :(得分:0)

解决方案是使用getDerivedStateFromProps()静态方法从上级组件获取状态作为道具,并使用这些道具初始化子组件的状态。这是代码:

将父组件状态作为道具传递给子组件:

<DataGraph graph={this.state} />

使用上述方法更新子组件状态:

class DataGraph extends Component {
  constructor() {
    super();
    this.state = {
      dataset: "",
      cc: "",
      cw: 0,
      ch: 0,
      bw: 0,
      bh: 0,
      xspacing: 0,
      yspacing: 0,
      barcolor: "",
    };
    this.myRef = React.createRef();
  }

  static getDerivedStateFromProps(props, state) {
    return {
      dataset: props.graph.dataset,
      cc: props.graph.cc,
      cw: props.graph.cw,
      ch: props.graph.ch,
      bw: props.graph.bw,
      bh: props.graph.bh,
      xspacing: props.graph.xspacing,
      yspacing: props.graph.yspacing,
      barcolor: props.graph.barcolor,
    };
  }

  drawChart() {
    const d = this.state.dataset.split`,`.map((x) => +x);
    const accessToRef = d3
      .select(this.myRef.current)
      .append("svg")
      .attr("width", this.state.cw)
      .attr("height", this.state.ch)
      .style("background-color", this.state.cc);

    accessToRef
      .selectAll("rect")
      .data(d)
      .enter()
      .append("rect")
      .attr("x", (d, i) => i * this.state.xspacing)
      .attr("y", (d, i) => this.state.ch - this.state.yspacing * d)
      .attr("width", this.state.bw)
      .attr("height", (d, i) => d * this.state.bh)
      .attr("fill", this.state.barcolor);
  }

  render() {
    this.drawChart();
    return (
      <>
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
          }}
          ref={this.myRef}
          className="pb-5"
        ></div>
      </>
    );
  }
}
getDerivedStateFromProps()是上面提到的静态方法,因此在使用时请牢记。另外,请勿在{{1​​}}或constructor()中初始化“ props”,否则将不起作用。谢谢,它奏效了,我讨厌Redux Boilerplate?。