javascript - 由于误用状态,数组未动态更新

标签 javascript node.js json reactjs state

单击单选按钮时,会将值从 0 更改为 1,反之亦然。
这是通过 2 个组件 Test.js 和 Graph_Test.js 完成的。
Test.js 是创建单选按钮并填充数组的地方。例如,当按下单选按钮 1 时,我希望它将 array[1] 中的值从 0 更改为 1 或 1 更改为 0。
因此,每当按下单选按钮时,它就会动态地更改数组。
然后使用该数组在 Graph_Test.js 中构建图表,根据哪些索引旁边有 1 值,将在图表上绘制相应的线。
例如,如果 array = [0,1,0,0] ,将为区域 1 绘制一条线。 因此,当该数组动态变化时,图表上的线条也会动态变化。

我正在测试我的代码。在 Graph_test 中,我输出数组 [0],当触摸单选按钮 [0] 时,该值应该更新。然而这并没有发生。

在 test.js 中,我使用了状态,这就是我的问题所在,因为初始数组是作为 prop 传递的,但它不是动态更新的。

Graph_test.js 有两个 props,通过数组和测试发送,测试将用于稍后构建图表。但目前不需要。

我尝试了很多尝试,但仍然没有取得任何进展,任何帮助将不胜感激/需要。

代码: 测试.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;

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

最佳答案

据我所知,React 不会与状态进行深度比较,因此,由于您重用了已经存在的数组,因此它具有与前一个数组相同的内存引用。

尝试这样的事情:

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

关于javascript - 由于误用状态,数组未动态更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61169081/

相关文章:

javascript - 仅使用 jquery 逐渐更改 div 颜色

node.js - 使用 firebase-admin 的云函数中 @firebase/database 的错误对等依赖关系

c# - 判断 Json 结果是对象还是数组

java - 尝试连接 JSON 服务器时出现异常

javascript - 使用 jquery 检查表中的行是否具有 css 类

javascript - 无法为 matter.js 设置动画

node.js - 动态解析 Jade 内容

python - 在 Django 项目中使用 Web 套接字的最佳方法是什么?

javascript - angularjs http post 到特定元素处的 json 数组

javascript - 获取 Dynamics CRM 2016 中字段的显示名称