【问题标题】:What happened with the render() after React Hooks?React Hooks 之后的 render() 发生了什么?
【发布时间】:2020-05-10 09:00:40
【问题描述】:

在 Hooks 之前,我们使用了很多基于类的 render(),它确实做到了,将之前的 DOM 与当前的 DOM 进行比较,如果它们不同,React 将重新渲染组件。

但是现在,使用 React Hooks,通常我们只使用 return() 来返回内容并渲染,我是对的吗?

return() 是否与 Hooks 之前的 render() 一样?如果不是,有什么区别?

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    return()render() 完全一样。如果将组件编写为函数,则使用return()

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    

    如果您将组件编写为类,则使用render()

    class Welcome extends React.Component {
      render() {
        return <h1>Hello, {this.props.name}</h1>;
      }
    }
    

    但是,在过去,您在功能组件中没有状态/生命周期方法。为了解决这个问题,React 引入了 Hooks。过去你必须在构造函数中定义状态,现在你在这样的函数中定义它:

    function ExampleWithManyStates() {
      const [age, setAge] = useState(42);
      const [fruit, setFruit] = useState('banana');
      const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
    }
    

    此外,您可以使用 this 帖子中提到的带有钩子的生命周期方法

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2021-04-23
      • 2021-09-20
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多