Опора не обновляется динамически - PullRequest
0 голосов
/ 11 апреля 2020

Когда нажата радиокнопка (набор кнопок, закодированных в Test. js), выполняется функция, называемая handleclick. В этом я обновляю массив, однако мне не удается отправить его в graph_test. js. Таким образом, graph_test. js получает начальный массив, заполненный нулями, но никогда не получает обновленные версии.
Я хочу получить массив из 0 и 1, каждый индекс представляет область. При нажатии кнопки значение 0/1 превращается в противоположное значение.
Мне нужно это динамическое обновление, как в graph_test.s, я собираюсь кодировать строки на графике, основываясь на том, что индексы в массиве имеют 1 рядом с ним. 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 array={array} testing={[]} />
    </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, где вызывается массив:

import React from 'react';
import $ from "jquery";
//<h1>{props.testing.map}</h1>
const Graph_Test = props => { 
  console.log(`ARRRAy ${props.array.length}`);
    return(
      <div>
        <div>
        {props.array && props.array.length > 0 && <p>{props.array[0]}</p> }
        </div>     
        <div>
        {props.testing && props.testing.map((item, idx) => { 
          return (
            <label key={idx}>
              <input className="region" type="radio" value={idx} />
              <span>{idx}</span> 
            </label>
          );
        })}  
        </div>
      </div >
    );
  };export default Graph_Test;

app. 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: [] };

  }
  // 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 }));
  }
  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}/>
            <Graph_Test testing = {this.state.apiResponse} array={[]}  />

            </div>      
            </div>

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

Я создал песочницу. Вы можете видеть 0, поэтому, когда радио-кнопка нажата, я хочу, чтобы она повернулась к 0, а затем, когда она нажимается снова, я хочу, чтобы она вернулась к 1. Это сделано с состояниями? Также не обращайте внимания на первый ряд переключателей, просто используйте его там для целей тестирования. В следующем ряду он должен работать https://codesandbox.io/s/arraypropproblem-8ec6d?file= / src / components / Test. js

1 Ответ

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

Ваш CodeSandbox возвращает ошибку выборки, но да, вы правы: благодаря реализации общего состояния, используемого между вашими двумя компонентами, обновление handleClick также будет корректно отражено в graph_test

Если они являются братьями и сестрами, поднять состояние до родительского компонента, и это должно сделать. Пример:

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isClicked: false
    };
  }

  handleClick = () => {
    this.setState({ ...this.state, isClicked: !this.state.isClicked });
  };

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click</button>
      </div>
    );
  }
}

export default Example;

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

...