Массив не обновляется динамически из-за неправильного использования состояний - PullRequest
0 голосов
/ 12 апреля 2020

При нажатии переключателя он изменяет значение с 0 на 1 или наоборот.
Это выполняется с помощью двух компонентов Test. js и Graph_Test. js.
Test. js это где переключатели созданы и массив заполнен. Например, когда нажата радиокнопка 1, я хочу, чтобы она изменила значение в массиве [1] с 0 на 1 или с 1 на 0.
Так что каждый раз, когда нажата радиокнопка, она будет динамически изменять массив.
Этот массив затем используется для построения графика в Graph_Test. js, в зависимости от того, какие индексы имеют 1 значение, рядом с ним будут построены соответствующие строки на графике.
Например, если array = [0,1,0,0] для области 1 будет проведена линия. Таким образом, этот массив будет динамически изменяться, как и линии на графике.

Я тестирую свой код. В Graph_test у меня есть выходной массив [0], и при касании радиокнопки [0] это значение должно обновиться. Однако этого не происходит.

В тесте. js, я использовал состояния, в которых моя проблема в том, что начальный массив доставляется в качестве опоры, но он не обновляется динамически.

Graph_test. js имеет два реквизита, которые отправляются через массив и тестирование, тестирование будет использоваться для построения графика позже. Но в данный момент не требуется.

Я перепробовал много попыток, и до сих пор никуда не денусь, любая помощь будет принята с благодарностью.

Код: Test. js:

// When radio buttons checked, change corresponding value in array if 0 change to 1 and if 1 change to 0
// This will be used in the graph component, and will enable the functionality of selcting one region or multiple region.
// As the graph will be plotted based on which regions are noted 1 in the array 
import $ from "jquery";
import Graph_Test from "./Graph_Test.js";
import React, { useState } from "react";
const Test = props => {
  const total_regions = (JSON.parse(JSON.stringify(props.test)).length); // gets the number of regions
  const [array, setArray] = useState(Array(total_regions.length).fill(0));
    //when a radio button is clicked change its corresponding in the array

//when a radio button is clicked change its corresponding in the array
const handleClick = (item, idx) => {
  if (array[idx] == 1) {
    array[idx] = 0;
  } else {
    array[idx] = 1;
  }
  setArray(array);
};

  return (   // displays radio buttons depending on the number of objects in json
    <div>
      <div>
        <Graph_Test  testing={[]} arrays={array}/>
      </div>
      <div>
        {props.test.map((item, idx) => { 
          return (
            <label key={idx}>
              <input className="region" type="radio" value={idx} onClick={() => handleClick(item, idx)}/>
              <span>{idx}</span> 
            </label>
          );
        })}  
      </div>
    </div>
  );
};
export default Test;

Graph_Test. js

import React from 'react';
import $ from "jquery";
//<h1>{props.testing.map}</h1>
const Graph_Test = props => { 

    return(
      <div>
        <div>
        {props.arrays && props.arrays.length > 0 && <p>{props.arrays[0]}</p> }
        </div>     
      </div >
    );
  };export default Graph_Test;

Приложение. js

import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import ReactPlayer from 'react-player'
import LeftPane from "./components/LeftPane.js";
import Video from "./components/Video.js";
//import Footer from "./components/Footer.js";
import Test from "./components/Test.js";
import Graph_Test from "./components/Graph_Test.js";
//import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { apiResponse: [] };
    this.state = {
      clicked: "no"
    };
  }
  // Comunicate with API
  callAPI() {
    fetch("http://localhost:9000/IntensityAPI") //React app talks to API at this url
      .then(res => res.json())
      .then(res => this.setState({ apiResponse: res }));
  }
  handleClick = () => {
  this.setState({ ...this.state, isClicked: "yes" });
  console.log("clicked");
};
  componentWillMount() {
    this.callAPI();
  }

  render() {
    return (
      <div className="App">
          <div class="row fixed-top fixed-bottom no-gutters"  >
            <div class="col-3 fixed-top fixed-bottom">
              <LeftPane></LeftPane>
            </div>
            <div class="offset-md-3 fixed-top fixed-bottom" >
              <Video></Video>
            </div>
            <div class=" col-3 fixed-bottom">
            <Test test = {this.state.apiResponse} handler={this.handleClick}/>
            <Graph_Test testing = {this.state.apiResponse} arrays={[]}  {...this.state}/>

            </div>      
            </div>

      </div>
    );
  }
}
export default App;
//  <Footer test = {this.state.apiResponse}/>

1 Ответ

1 голос
/ 12 апреля 2020

AFAIK React не выполняет глубокое сравнение с состоянием, поэтому, поскольку вы повторно используете уже существующий массив, он имеет ту же ссылку на память, что и предыдущий.

Попробуйте что-то вроде этого:

const handleClick = (item, idx) => {
  const newArray = [...array]
  if (newArray[idx] == 1) {
    newArray[idx] = 0;
  } else {
    newArray[idx] = 1;
  }
  setArray(newArray);
};
...