【问题标题】:update the UI in React using render method使用 render 方法更新 React 中的 UI
【发布时间】:2021-10-18 18:52:40
【问题描述】:

当我阅读 react 文档时,他们说“the only way to update the UI is to create a new element, and pass it to ReactDOM.render()”。由于我在下面创建了这样的代码。

function Clock() {
 // console.log('clock called'); 

  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
                  )

  return (
    element
  );
}


ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
  );

//every second call Clock
setInterval(Clock, 1000);

时钟组件每秒都会被调用一次,因此它每秒都会创建一个新元素。当 Clock 组件传递给 render 方法时。但用户界面没有更新。为什么?我没有每秒调用一次渲染方法。因为文档没有说:“每秒调用一次渲染方法”。我以为在创建新元素时,会自动调用 render 方法。我的想法好不好?

在文档中如下代码

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

在这里他们也每秒调用一次渲染方法。但在文档中,他们并没有指定每次更新都调用 render 方法。

【问题讨论】:

    标签: reactjs user-interface render


    【解决方案1】:

    要实现组件的动态更新,您需要使用状态挂钩,例如 useEffect()useState

    //import { useState } from 'react';
    const { useState, useEffect } = React;
    
    function Clock() {
    
    const time = new Date();
    // a hook to maintain the state
     const [ state, setState] = useState();
    // a listener to handle changes in the parameters of the array, in our case time
      useEffect(() => {
        setState(time.toLocaleTimeString());
      }, [time])
      
      const element = (
        <div>
          <h1>Hello, world!</h1>
          <h2>It is {state}.</h2>
        </div>
                      )
    
      return (
        element
      );
    }
    
    
    ReactDOM.render(
        <Clock/>,
        document.getElementById('root')
      );
    
    
    

    在发布的代码中,我们使用useEffect() 挂钩来响应Date() 对象中的任何更改。在回调函数之后传入数组中。

    这个钩子有什么作用?

    它调用useState()钩子来更新我们的状态变量,我称之为state,每当时间改变时都会相应地显示出来。

    【讨论】:

    • 你的解释是新概念。但我没想到会这样。我的问题是,要更改 UI,我们是否需要一次又一次地调用 ReactDOM.render() 方法?或者当我们刚刚创建一个新元素时,会不会自动调用 render 方法来通过 React 重新渲染元素?
    • 没有。 useEffect() 中的参数数组中的任何更改都将自行触发重新渲染。你不需要多次调用 render 方法
    • 如果不使用useEffect(),我需要一次又一次地调用render方法来改变UI。我的想法是对还是错?
    • 不幸的是,render方法不应该被多次调用,你需要使用组件状态。你可以在函数中使用setInterval,通过创建一个新的日期对象而不是useEffect来每秒更新状态,但是相信我使用useEffectuseState会让你的React开发之旅变得更容易。
    猜你喜欢
    • 2016-06-07
    • 2018-02-25
    • 2016-01-19
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多