状态更改后,功能组件不会重新呈现[React]

时间:2020-01-17 16:07:46

标签: javascript reactjs

我正在尝试构建一个React应用程序,我可以在其中输入我的体重和身高,它将计算我的BMI值并将其显示在图表上。我不想将所有内容都制作成一个组件,所以我将其划分为多个小组件。

这是主要的应用程序组件:

const App_function = () => {
  const [arrayBMI, setArrayBMI]=useState([]);
  const [dateArray, setDateArray]=useState([]);

  const handlerMain = (heightData, weightData) => {
    const valueOfBMI = weightData / (heightData/100*heightData/100);
    console.log(valueOfBMI);
    const repMainArray = arrayBMI;
    repMainArray.push(valueOfBMI);
    setArrayBMI(repMainArray);

    const repDateArray = dateArray;
    let currentDateData = new Date();
    let day = currentDateData.getDate();
    if(day < 10) {
      day = '0' + day;
    }
    let month = currentDateData.getMonth() + 1;
    if(month < 10) {
      month = '0' + month;
    }
    let year = currentDateData.getFullYear();
    let date = `${day}-${month}-${year}`;
    repDateArray.push(date);
    setDateArray(repDateArray);
  }

  return (
    <div>
      <Data handlerFunction={handlerMain}/>
      <Diagram arrayMain={arrayBMI} arrayOfDate={dateArray}/>
      <div>{arrayBMI[0]} a {arrayBMI[1]}</div>
      <StoragE/>
    </div>
  );
}

这是数据组件:

function data_function(props) {

  function formCloser(event) {
    event.preventDefault();
    let heightField = event.target.querySelector('#height').value;
    let weightField = event.target.querySelector('#weight').value;
      props.handlerFunction(heightField, weightField);
        event.target.querySelector('#height').value='';
        event.target.querySelector('#weight').value='';
  }


  return (
    <div className="main-div">
      <p className="paragraph-boy">BMI Calculator</p>
      <form onSubmit={formCloser}>
        <div className="inputs">
          <div className="input_fields">
            <label htmlFor="weight">Weight (in kg)</label>
          <input type="text" id="weight" placeholder="50" autoComplete="off"></input>
          </div>
          <div className="input_fields">
            <label htmlFor="height">Height (in cm)</label>
          <input type="text" id="height" placeholder="175" autoComplete="off"></input>
          </div>
        </div>
        <button type="submit" className="btn">Calculate BMI</button>
      </form>
    </div>
  );
}

export default data_function;

您可以看到App Component是Data Component的父级。每当我填写表格并点击“提交”时,它就会触发handlerFunction并传递来自 数据组件到应用程序组件。发送到App Component的数据用于计算BMI,然后将其值推入arrayBMI(App Component中的状态)。我不明白为什么提交后不重新呈现应用程序组件。

过去2天,我可能正在尝试解决由它引起的问题。今天,我发现当任何状态的值发生更改时我的主应用程序组件都不会重新渲染,我也不知道为什么。

2 个答案:

答案 0 :(得分:0)

替换此代码

const repMainArray = arrayBMI;
    repMainArray.push(valueOfBMI);

作者

const repMainArray = [...this.sate.arrayBMI,valueOfBMI] ;

const repDateArray.push(date);

答案 1 :(得分:-1)

https://reactjs.org/docs/hooks-reference.html#usecallback中包装主处理程序函数以具有依赖项(用于侦听更改的内容)。