首页 > 解决方案 > react js中无法通过props发送状态的更新值

问题描述

我正在尝试将状态值从父组件发送到子组件。最初状态值是空的。在 API 调用之后,状态值得到更新,但我的道具采用初始空值。

class Metrics extends React.Component {
constructor(props) {
    super(props);
this.state.result:[];
}

  submit = e => {
     e.preventDefault();
    var URL =
     "http://localhost:8080/fetchAnalysisData;
    this.setState({ formsubmit: true });

    fetch(URL, {
      method: "GET"
    })
      .then(res => res.json())
      .then(data => {
        console.log("Response Success!!");
        this.setState({ result: data });
      });
  };

render(){
return(

<Button onClick={this.submit}
                   fontSize: "small",
                    marginLeft: "30%"
                  }}
                >
                  VIEW RESULT
                </Button>
<div className={this.state.formsubmit ? "showDisplay" : "hide"}>
 <DipslayBarChart result={this.state.result}></DipslayBarChart>
</div>
)
}

子组件:

class DipslayBarChart extends React.Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
            <div>
              <BarChart width={500} height={300} data={this.props.result}>
                      <XAxis dataKey="Date" />
                      <YAxis />
                      <Tooltip cursor={false} />
                      <Legend />
                      <Bar dataKey="Success" stackId="a" fill="#068f12" label />
                      <Bar
                        dataKey="Failure"
                        stackId="a"
                        fill="#ec0b0b"
                      />
                    </BarChart>
            </div>
        )
    }

}

状态更新后如何更新道具值?

标签: javascriptreactjs

解决方案


像这样写你的构造函数,

constructor(props) {
    super(props);
    this.state={
      result:[]
    }
}

推荐阅读