簡體   English   中英

React-無法通過prop設置組件的狀態

[英]React - can't set component's state from props

反應很新,我面臨着意外的行為。

我正在嘗試使用我的react應用程序可視化來自數據庫的數據(數據可視化的ChartJS)

這是我的App.js(我從create-react-app ),在其中我從服務器的端點作為JSON文件獲取數據,並將其傳遞給BarGraph組件:

class App extends Component {
    constructor() {
        super();
        this.state = {
            records_lst : [],
        }
    }

    componentWillMount() {
        this.fetchData();
    }

    fetchData() {
        let data = fetch('http://127.0.0.1:5000/api/dbrecords')
            .then((resp) => {
                resp.json().then((res) => {
                    this.setState({
                        records_lst : res,
                    });
                });
            })
    }

    render() {
        return (<div className="App">
          <BarGraph
              label1={'Toolbox - whole'}
              label2={'tu-ma'}
              textTitle={'Just a Test'}
              times={this.state.records_lst.length}
          />
        </div>);
    }
}

狀態records_lst僅保存一個json數組,每個json是數據庫的一行。

現在,我想做的是通過計算records_lst數組的長度來計算數據庫中有多少行,並將其發送到BarGraph組件(如下所示)以顯示具有該值的單個條形,但是出於某種原因,我不能!

這是條形圖:

class BarGraph extends Component {
constructor(props) {
    super(props);
    this.state = {
        chartData : {
            labels: [this.props.label1],
            datasets: [
                {
                    label: [this.props.label2],
                    data: [this.props.times]
                }
            ]
        }
    }
}

我注意到的是,組件的屬性正確,因此可以正確計算“時間”,但是組件的狀態沒有選擇該數字。 Chrome的devtool的屏幕截圖,為了清晰起見

最后,如果在App.js中,當我使用所有道具調用時,我將把times={44} (或任何其他數字)顯示為正常。 我猜出於相同的原因, label : [this.props.label2]可以工作。

我在這里想念什么?

謝謝!

采用

data: [props.times]

代替

data: [this.props.times]

並且constructor將僅被調用一次,並且是在您第一次加載組件時,因為到那時您可能將沒有必要的props ,因為您是異步獲取它的。 這樣更好地使用它。

    componentwillReciveprops(props){
this.setState({data:props.times})
}

@mayak在上面正確說過......構造函數只被調用一次

afaik,不要在構造函數中將您的道具置入您的狀態。

在render方法中輪詢這些道具。

class BarGraph extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        var data = {
            chartData : {
                labels: [this.props.label1],
                datasets: [
                    {
                       label: [this.props.label2],
                       data: [this.props.times]
                    }
                ]
            }
        return (
             <div>hello</div>
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM