无法通过React JS中的道具发送状态的更新值

时间:2019-05-06 07:18:30

标签: javascript reactjs

我正在尝试将状态值从父组件发送到子组件。状态值最初为空。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>
        )
    }

}

状态更新后,如何更新prop值?

2 个答案:

答案 0 :(得分:2)

这样写你的构造函数,

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

答案 1 :(得分:0)

此外,如果您不在构造函数中使用道具,则无需声明构造函数。您可以这样声明状态

state={
  result:[]
} 
相关问题