zoukankan      html  css  js  c++  java
  • React函数式组件值之useContext()和useReducer()

    一、useContext

       useContext()的出现,方便了我们在组件之间的状态共享。

     1 import React, { useContext } from "react";
     2 import ReactDOM from "react-dom";
     3 const TestContext= React.createContext({});
     4 const Navbar = () => {
     5   const { username } = useContext(TestContext)
     6   return (
     7     <div className="navbar">
     8       <p>{username}</p>
     9     </div>
    10   )
    11 }
    12 const Messages = () => {
    13   const { username } = useContext(TestContext)
    14   return (
    15     <div className="messages">
    16       <p>1 message for {username}</p>
    17     </div>
    18   )
    19 }
    20 function App() {
    21   return (
    22   <TestContext.Provider 
    23     value={{
    24       username: 'superawesome',
    25     }}
    26   >
    27     <div className="test">
    28       <Navbar />
    29       <Messages />
    30     </div>
    31   <TestContext.Provider/>
    32   );
    33 }
    34 const rootElement = document.getElementById("root");
    35 ReactDOM.render(<App />, rootElement);

    二、useReducer

      useReducer 类似 redux 中的功能,相较于 useState,它更适合一些逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等等的特定场景, useReducer 总共有三个参数

    • 第一个参数是 一个 reducer,就是一个函数类似 (state, action) => newState 的函数,传入 上一个 state 和本次的 action
    • 第二个参数是初始 state,也就是默认值,是比较简单的方法
    • 第三个参数是惰性初始化,这么做可以将用于计算 state 的逻辑提取到 reducer 外部,这也为将来对重置 state 的 action 做处理提供了便利
     1 function reducer(state, action) {
     2   switch (action.type) {
     3     case 'increment':
     4       return {count: state.count + 1};
     5     case 'decrement':
     6       return {count: state.count - 1};
     7     default:
     8       throw new Error();
     9   }
    10 }
    11 function App() {
    12   const [state, dispatch] = useReducer(reducer, {count: 0});
    13   return (
    14     <>
    15       点击次数: {state.count}
    16       <button onClick={() => dispatch({type: 'increment'})}>+</button>
    17       <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    18     </>
    19   );
    20 }

     

  • 相关阅读:
    querySelectorAll和getElementsByClassName获取元素的区别
    移动端的点透事件
    formidable处理node.js的post请求
    Node中流的概念
    关于Node.js中的路径问题
    前端设计模式——原型模式
    JavaScript中的循环和闭包
    为什么给函数表达式添加函数名
    作为一个初学者如何简单地理解闭包
    JS的with关键字到底是什么?
  • 原文地址:https://www.cnblogs.com/guanghe/p/14179059.html
Copyright © 2011-2022 走看看