简体   繁体   English

如何从 React js 中的状态获取图表 js 饼图的数据?

[英]How to fetch data for chart js Pie Chart from State in React js?

As I am new to react i have been struggling to pass data from my state to the chartjs dynamically...what I need is when ever user updates the Textbox and asks for the Output, the Pie chart should update itself automatically according to the output...i have stored the output values in the state but Pie chart is not allowing me to Pass state as data...由于我是新手,我一直在努力将数据从我的状态动态传递到 chartjs……我需要的是当用户更新文本框并要求输出时,饼图应该根据输出自动更新...我已将输出值存储在状态中,但饼图不允许我将状态作为数据传递...

Here's a Link to the Code Sandbox https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark这是代码沙箱的链接https://codesandbox.io/s/autumn-mountain-sv1qk?fontsize=14&hidenavigation=1&theme=dark

 class Buyer extends Component {

        constructor(props) {
            super(props);
            this.state = {
                income: 100000,
                percent: 13,
                totalTax: '',
                grossPrice: '',
                otherValues: '',
            }
        }






PieChart = (Gross,totalTax) => {
    let GrossPrice = Gross  ;
    let TotalTax = totalTax ;
    let data = [GrossPrice,TotalTax]
    let Pie = {
            labels: ['Total Tax', 'Gross Price'],   
            datasets: [{
                data: data,
                backgroundColor: [
                    '#1ca5b6',
                    '#89ba2b',
                ],

            }]

        }

    }



handleIncome = (event) => {
    let income = event.target.value
    this.handleData(income, this.state.percent)
    console.log(this.state)

}

handlePercent = (event) => {
    let Percent = event.target.value
    this.handleSliderData(this.state.income, Percent)

}


// From Slider
sliderIncome = (event) => {
    this.setState({ income: event })
    this.handleSliderData(event, this.state.percent)
    // console.log(this.state)

}

sliderPercent = (event) => {
    this.setState({ percent: event })
    this.handleSliderData(this.state.income, event)

}


handleData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice: //some Calculations
        otherValues: //some Calculations

    })



    console.log(this.state)
}




handleSliderData = (income, Percent) => {
    this.setState({
        income: income,
        percent: Percent,
        totalTax: //some Calculations
        grossPrice://some Calculations
        otherValues://some Calculations
    })
    this.PieChart(this.state.grossPrice,this.state.totalTax)
    // console.log(this.state)

}


render() {
            return ( 
              <div>
                    <div >
                        <Card s>
                            <PieChart data={this.PieChart} width={600} height={300} />
                        </Card>
                    </div>
                </Col>

              )
     }

I have tried creating a function for the pie chart but was not able to get through...any help would be appreciated..thanks!!我曾尝试为饼图创建一个函数,但无法通过...任何帮助将不胜感激...谢谢!

I think there are a few problems with the code.我认为代码存在一些问题。 this.PieChart function doesn't return anything now. this.PieChart 函数现在不返回任何内容。 From giving the code a quick glance, I can see that you are trying to pass the props needed for the PieChart component from this.PieChart function.通过快速浏览代码,我可以看到您正在尝试从 this.PieChart 函数传递 PieChart 组件所需的道具。 Return whatever you need as prop for the component and also call the function inside the JSX using parenthesis, passing the needed parameters into the function.返回您需要的任何组件作为 prop 并使用括号调用 JSX 内的函数,将所需的参数传递给函数。

PieChart = (Gross,totalTax) => {
let GrossPrice = Gross  ;
let TotalTax = totalTax ;
let data = [GrossPrice,TotalTax]
let Pie = {
        labels: ['Total Tax', 'Gross Price'],   
        datasets: [{
            data: data,
            backgroundColor: [
                '#1ca5b6',
                '#89ba2b',
            ],

        }]

    }

}
return Pie; //or whatever data you need for the component

Also,还,

 <PieChart data={this.PieChart(this.state.grossPrice, this.state.totalTax)} width={600} height={300} />

Also, keep in mind to use proper naming conventions.另外,请记住使用正确的命名约定。 Functions should be in camel case( this.PieChart should be named this.pieChart ).函数应该是驼峰式的( this.PieChart 应该命名为 this.pieChart )。 Try using different names for the component and function.尝试为组件和函数使用不同的名称。 This shall solve a lot of problems you might run into这将解决您可能遇到的很多问题

Update: I have updated the sandbox you have shared.更新:我已经更新了您共享的沙箱。 Hope this helps.希望这可以帮助。 https://codesandbox.io/s/friendly-mahavira-79n2s https://codesandbox.io/s/friendly-mahavira-79n2s

I think i found the solution for the particular problem...i order to update the data in the piechart dynamically using state we have create a state in the constructor(props) like so...我想我找到了特定问题的解决方案......我为了使用状态动态更新饼图中的数据,我们在constructor(props)创建了一个状态,就像这样......

constructor(props) {
        super(props);
        this.state = {
            income: '',
            percent: '',
            totalTax: '',
            grossPrice: '',
            otherValues: '',
            Data: {} 
        }

    }

Then i have used componentDidMount() to mount the initial state of the PieChart like So....然后我使用componentDidMount()来挂载 PieChart 的初始状态,就像 So....

componentDidMount() {

        let runscore = [100,200];



        this.setState(
            {
                Data: {
                    labels: [
                        'Purple',
                        'Yellow',

                    ],
                    datasets: [
                        {

                            data: runscore,
                            backgroundColor: [
                                '#1ca5b6',
                                '#89ba2b',

                            ]
                        }
                    ]
                }
            });


    }

then i created a function PieChart = (Gross,totalTax) that fetches data from another functions and used that to set state in Data like so...然后我创建了一个函数PieChart = (Gross,totalTax)从另一个函数中获取数据并使用它来设置数据中的状态,就像这样......

PieChart = (Gross,totalTax) => {
        let runscore = [Gross,totalTax];
        this.setState({
            Data: {
                labels: [
                    'Gross Price',
                    'Total Tax',

                ],
                datasets: [
                    {
                        data: runscore,
                        backgroundColor: [
                            '#1ca5b6',
                            '#89ba2b',
                        ]
                    }
                ]
            }
        });


        }

For now this is not updating the state in sync with the current state but i gets the work done...i hope this helps others...现在这不是与当前状态同步更新状态,但我完成了工作......我希望这有助于其他人......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM