react中hooks的理解

引入状态
在这里插入图片描述
useContext():共享状态钩子,函数里面套函数,然后是函数式组件。

import React, { useContext } from "react";
const Ceshi = () => {
  const AppContext = React.createContext({});
  const A = () => {
    const { name } = useContext(AppContext);
    return (
      <p>
        我是A组件的名字{name}
        <span>我是A的子组件{name}</span>
      </p>
    );
  };
  const B = () => {
    const { name } = useContext(AppContext);
    return <p>我是B组件的名字{name}</p>;
  };
  return (
    <AppContext.Provider value={
   
   { name: "hook测试" }}>
      <A />
      <B />
    </AppContext.Provider>
  );
};
export default Ceshi;

在这里插入图片描述
在这里插入图片描述

import React, { useReducer } from "react";

const AddCount = () => {
  const reducer = (state, action) => {
    if (action.type === "add") {
      return {
        ...state,
        count: state.count + 1,
      };
    } else {
      return state;
    }
  };
  const addcount = () => {
    dispatch({
      type: "add",
    });
  };
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <>
      <p>{state.count}</p>
      <button onClick={addcount}>count++</button>
    </>
  );
};
export default AddCount;

在这里插入图片描述

https://www.jianshu.com/p/d600f749bb19

おすすめ

転載: blog.csdn.net/liulang68/article/details/121522006
おすすめ