zoukankan      html  css  js  c++  java
  • React Hooks (React v16.7.0alpha)

    什么是Hooks

    “Hooks” 本意是”钩子“的意思。在 React 里,hooks 就是一系列特殊的函数,使函数组件 (functional component) 内部能够”钩住“ React 内部的 state 和 life-cycles。

    为什么使用Hooks

    刚刚接触react时候非常喜欢用函数式组件,因为太简洁了写起来非常快,然后然后。。写到后面发现很多自己以前写的组件需要改。。为什么呢,因为自己当时写的时候考虑的不周到,后期发现很多地方都需要生命周期和状态来进行渲染优化,然后就是大量修改函数式为classComponent。所以现在起手一般都是classComponent,只有极简单的组件用函数式比如列表item啥的。

    使用Hooks的规则

    • 只能在顶层调用Hooks 。不要在循环,条件或嵌套函数中调用Hook
    • 只能在functional component(函数式组件)中使用

    Hooks

    State Hook

    • 即在函数式中使用state
    import { useState } from 'react';
    
    function Example() {
      const [count, setCount] = useState(0);
      //const [age, setAge] = useState(42);
      //const [fruit, setFruit] = useState('banana');
      //const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>
            Click me
          </button>
        </div>
      );
    }
    
    • useState的参数就是以前state的初始值。
    • useState返回的值中第一个参数是以前的state,第二个参数是setState,不过以前我们只有一个state,现在可以自由命名,更直观了,比如上面的agesetAgefruitsetFruit

    Effect Hook

    • effect Hook使我们可以使用生命周期了
    function FriendStatusWithCounter(props) {
      const [count, setCount] = useState(0);
      useEffect(() => {
        document.title = `You clicked ${count} times`;
      });
    
      const [isOnline, setIsOnline] = useState(null);
      useEffect(() => {
        ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
        return () => {
          ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
        };
      });
    
      function handleStatusChange(status) {
        setIsOnline(status.isOnline);
      }
      // ...
    
    • 每当 React更新之后,就会触发 useEffect(在第一次 render 和每次 update 后触发)。

    Custom Hooks

    • 有时,我们希望在组件之间重用一些有状态逻辑。
    • 首先,我们将这个逻辑写到useFriendStatus:返回朋友在线的状态isOnline
    import { useState, useEffect } from 'react';
    
    function useFriendStatus(friendID) {
      const [isOnline, setIsOnline] = useState(null);
    
      function handleStatusChange(status) {
        setIsOnline(status.isOnline);
      }
    
      useEffect(() => {
        ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
        return () => {
          ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
        };
      });
    
      return isOnline;
    }
    
    • 然后我们在其他组件中使用
    function FriendListItem(props) {
      const isOnline = useFriendStatus(props.friend.id);
    
      return (
        <li style={{ color: isOnline ? 'green' : 'black' }}>
          {props.friend.name}
        </li>
      );
    }
    

    Other Hooks

    • 你可能会发现一些不太常用的内置Hook很有用。
    • useContext:
    function Example() {
      const locale = useContext(LocaleContext);
      const theme = useContext(ThemeContext);
      // ...
    }
    
    • useReducer
    function Todos() {
      const [todos, dispatch] = useReducer(todosReducer);
      // ...
    

    总结

    以后可以更愉快的写functional component(函数式组件)了

    参考

    react官方Hooks简介

    Hooks例子

    最后

    大家好,这里是「 十年雪落 」,这个博客主要用于记录一个菜鸟程序猿的成长之路。这也是自己第一次做博客,希望和大家多多交流,一起成长!文章将会在下列地址同步更新……
    博客园:www.cnblogs.com/maopixin/

  • 相关阅读:
    apache phoenix查询缓慢问题
    hbase replication原理分析
    ServerSocketChannel实现多Selector高并发server
    hbase hmaster故障分析及解决方案:Timedout 300000ms waiting for namespace table to be assigned
    mapreduce出现类似死锁情况
    【转】How-to: Enable User Authentication and Authorization in Apache HBase
    最近的一些杂念思考
    我究竟该成为什么样的一个人
    解决linux下 使用netcore生成图片报错的问题:The type initializer for 'Gdip' threw an exception
    linux 编译安装nginx
  • 原文地址:https://www.cnblogs.com/maopixin/p/9869361.html
Copyright © 2011-2022 走看看