如何通过使用特定的数组索引来更改状态数组的对象值

时间:2019-12-11 10:06:12

标签: javascript reactjs jsx

我正在尝试使用setState从状态数组更改对象键的值。更改的方式应是仅从索引i的数组更改对象的特定值。该索引如下传递

import React from "react";
import {Button} from 'react-bootstrap';

class StepComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [
                { 
                    step: "Step1",
                    visited: false
                },
                { 
                    step: "Step2",
                    visited: false
                },
                { 
                    step: "Step3",
                    visited: false
                }
            ]
        };
    }
    nextStep(i) {

        //Change the visited value of object from data[i] array from false to true
        //Something like below

        this.setState({
            data[i]:visited to true
        })
    }

    render(){
        let visitSteps = this.state.data;
        return(
            <div>
                {visitSteps.map((visitedStep, index) => (
                    <div key={index}>
                        <p>{visitedStep.step}</p>
                        <Button onClick={() => this.nextStep(i)}>Continue</Button>
                    </div>
                ))}
            </div>
        )
    }
}

export default StepComponent

根据在每个onClick事件上给以嘘声的示例,被访问的特定对象值的值从false更改为true

2 个答案:

答案 0 :(得分:3)

您可以创建一个数组,该变量等于您的数据,更改作为输入传递的索引,然后调用传递新数组的set状态。

    nextStep(i) {
        let visitesList = [...this.state.data];
        visitesList[i].visited = true;

        this.setState({
            data: visitesList
        })
    }

如果您一次只想实现一个步骤,则可以使用地图功能

  nextStep(i) {
    this.setState({
      data: this.state.data.map((e, index) => {
        e.visited = i === index;
        return e;
      })
    });
  }

此外,在nextStep上调用Button时,请使用nextStep(index)

进行调用

答案 1 :(得分:0)

更改数组的特定对象属性。

class App extends React.Component {
      state = {
        data:[
                { 
                    step: "Step1",
                    visited: false
                },
                { 
                    step: "Step2",
                    visited: false
                },
                { 
                    step: "Step3",
                    visited: false
                }
            ]
  };
  handleClick = item => {
    const { data } = this.state;
    let obj = data.find(a => a.step === item.step);
    obj.visited = true;
    let filtered = data.filter(a => a.step !== item.step);
    this.setState({ data: [obj, ...filtered] });
  };
  render() {
  console.log(this.state.data);
    return (
      <div>
        {this.state.data.map(a => (
          <button key={a.step} style={{ color: a.visited ? "red" : "" }} onClick={() => this.handleClick(a)}>
            {a.step}
          </button>
        ))}
      </div>
    );
  }
}

Live Demo