简体   繁体   English

React-无法通过prop设置组件的状态

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

Quite new to react, I'm facing an unexpected behavior. 反应很新,我面临着意外的行为。

I'm trying to visualize data that comes from a database with my react app (ChartJS for the data viz) 我正在尝试使用我的react应用程序可视化来自数据库的数据(数据可视化的ChartJS)

This is my App.js (I started from create-react-app ) where I fetch the data from the server's endpoint as a JSON file and I pass it to my BarGraph component: 这是我的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>);
    }
}

the state records_lst just holds an array of jsons, each of which is one row of the database. 状态records_lst仅保存一个json数组,每个json是数据库的一行。

Now, what I'm trying to do is to count how many rows are in the database by counting the length of the records_lst array and send it to the BarGraph component (below) to show one single bar with that value, but for some reason, I can't! 现在,我想做的是通过计算records_lst数组的长度来计算数据库中有多少行,并将其发送到BarGraph组件(如下所示)以显示具有该值的单个条形,但是出于某种原因,我不能!

Here is the 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]
                }
            ]
        }
    }
}

What I noticed is that the props of the component are correct, so "times" is calculated correctly, but the state of the component doesn't pick that number. 我注意到的是,组件的属性正确,因此可以正确计算“时间”,但是组件的状态没有选择该数字。 Screenshot of Chrome's devtools here for clarity Chrome的devtool的屏幕截图,为了清晰起见

Finally, if in App.js, when I invoke with all the props, I put times={44} (or any other number) the graph shows up normally. 最后,如果在App.js中,当我使用所有道具调用时,我将把times={44} (或任何其他数字)显示为正常。 I guess for the same reason label : [this.props.label2] works too. 我猜出于相同的原因, label : [this.props.label2]可以工作。

What am I missing here? 我在这里想念什么?

Thanks! 谢谢!

use 采用

data: [props.times]

instead of 代替

data: [this.props.times]

and the constructor will get called only once and it is when you load your component for the first time since by then you probably wont have the necessary props with you since you are getting it asynchronously. 并且constructor将仅被调用一次,并且是在您第一次加载组件时,因为到那时您可能将没有必要的props ,因为您是异步获取它的。 so better you use it like this. 这样更好地使用它。

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

@mayak said it correctly above...... the constructor only gets called once @mayak在上面正确说过......构造函数只被调用一次

afaik, do not put your props into your state in the constructor. afaik,不要在构造函数中将您的道具置入您的状态。

poll these props inside the render method. 在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