简体   繁体   English

反应。 如何将setState中的键与数组索引一起使用?

[英]React. How to use the keys in setState with array indexes?

So, this is my code. 所以,这是我的代码。 I have a simple question just about how I can use the state element with indexin key ? 我有一个简单的问题,关于如何将state元素与indexin key In this case I need to set the different values for different data index elements. 在这种情况下,我需要为不同的data索引元素设置不同的值。

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class Chart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            labels: ["All", "Done", "Active"],
            datasets: [{
                label: "Todos",
                backgroundColor: 'grey',
                borderColor: 'green',
                data: [0, 0, 0]
            }]
        };
    }

    getTodosList = (todos) => {
        const all = [];
        const active = [];
        const done = [];

        todos.filter(todo => {
            if (todo.status === 'active') {
                active.push(todo);
            } else if (todo.status === 'all') {
                all.push(todo);
            } else if (todo.status === 'done') {
                done.push(todo);
            }
        });

        this.setState({
            datasets[0].data[0]: all, // error
            datasets[0].data[1]: active, // error
            datasets[0].data[2]: done // error
        });
    }

It's simple: 这很简单:

this.setState({
    datasets: [...this.state.datasets,
        {
            data: [all.length, active.length, done.length]
        }
    ]
});

Start to think like Redux think. 开始像Redux那样思考。 Use pure functions. 使用纯函数。 It's will help you. 它会为您提供帮助。 Also I understand based on your starts data - you probably need to use the length of your items ... 我也根据您的开始data理解-您可能需要使用itemslength ...

The setState function doesn't know which object it has to replace with your code. setState函数不知道必须用代码替换哪个对象。 You're also not accessing the datasets variable properly, it should be this.state.datasets . 您也没有正确访问数据集变量,应该是this.state.datasets You could do something like: 您可以执行以下操作:

let datasets = this.state.datasets.slice();
datasets[0].data[0] = all;
datasets[0].data[1] = active;
datasets[0].data[2] = done;
this.setState({datasets});

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

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