Hooks

2020-06-23  本文已影响0人  海豚先生的博客

组件类的几个缺点。

  • 大型组件很难拆分和重构,也很难测试。
  • 业务逻辑分散在组件的各个方法之中,导致重复逻辑或关联逻辑。
  • 组件类引入了复杂的编程模式,比如 render props 和高阶组件。

hooks的由来

常用钩子

useState():状态钩子

import React, { useState } from "react";
export default function  Button()  {
  const  [buttonText, setButtonText] =  useState("Click me,   please");
  function handleClick()  {
    return setButtonText("Thanks, been clicked!");
  }
  return  <button  onClick={handleClick}>{buttonText}</button>;
}

useContext():共享状态钩子

// app.js
<AppContext.Provider value={{
  username: 'superawesome'
}}>
  <div className="App">
    <Navbar/>
    <Messages/>
  </div>
</AppContext.Provider>
// 创建一个context
<script>
const AppContext = React.createContext({});
</script>
// navbar.js
<script>
const Navbar = () => {
  const { username } = useContext(AppContext);
  return (
    <div className="navbar">
      <p>{username}</p>
    </div>
  )
}
</script>
// messages.js
<script>
const Messages = () => {
  const { username } = useContext(AppContext)
  return (
    <div className="messages">
      <p>1 message for {username}</p>
    </div>
  )
}
</script>

useReducer():action 钩子

// reducer.js
const myReducer = (state, action) => {
  switch(action.type)  {
    case('countUp'):
      return  {
        ...state,
        count: state.count + 1
      }
    default:
      return  state;
  }
}
// app.js
function App() {
  const [state, dispatch] = useReducer(myReducer, { count:   0 });
  return  (
    <div className="App">
      <button onClick={() => dispatch({ type: 'countUp' })}>
        +1
      </button>
      <p>Count: {state.count}</p>
    </div>
  );
}

useEffect():副作用钩子

const Person = ({ personId }) => {
  const [loading, setLoading] = useState(true);
  const [person, setPerson] = useState({});

  useEffect(() => {
    setLoading(true); 
    fetch(`https://swapi.co/api/people/${personId}/`)
      .then(response => response.json())
      .then(data => {
        setPerson(data);
        setLoading(false);
      });
  }, [personId])

  if (loading === true) {
    return <p>Loading ...</p>
  }

  return (
    <div>
      <p>You're viewing: {person.name}</p>
      <p>Height: {person.height}</p>
      <p>Mass: {person.mass}</p>
    </div>
  )
}
上一篇 下一篇

猜你喜欢

热点阅读