【问题标题】:Prop not updating dynamically道具不动态更新
【发布时间】:2020-07-24 08:46:58
【问题描述】:

当单击单选按钮(Test.js 中编码的一组按钮)时,会执行一个名为 handleclick 的函数。在此我更新了数组,但是我无法将其重新发送到 graph_test.js。因此,graph_test.js 接收到填充了 0 的初始数组,但它从未接收到更新的版本。
我想要的是一个 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

【问题讨论】:

    标签: javascript node.js json reactjs react-props


    【解决方案1】:

    您的代码框返回一个获取错误,但是您是对的:通过实现一个通用状态,在您的两个组件之间使用,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;
    

    并将此状态传递给您要在其中使用它的任何其他子组件

    【讨论】:

    • 谢谢@Slimcody,我已经搞砸了,但在各州苦苦挣扎,你能给我举个例子吗
    • 添加了一个简单的例子。还有一个类似的问题,代码更详细stackoverflow.com/questions/36143767/…
    • 不,兄弟姐妹中不需要构造函数,它们也可以是简单的无状态功能组件(但不要忘记将它们作为输入传递道具)
    • 我为您制作了这个简化的沙箱,您可以在其中看到它的工作原理,您可以对其进行更新以适应您的需要 codesandbox.io/s/small-architecture-tvxmg?file=/src/App.js
    • 不,它按原样工作,它被称为扩展运算符,它基本上复制一个元素并在最后添加新项目。对于简化的沙箱,不需要它,但如果您在您的状态中存储了更多信息,那么它应该用于不覆盖其余部分
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2020-10-23
    • 2023-01-28
    相关资源
    最近更新 更多