我正在尝试理解和练习 React 钩子。我有以下代码。
import React, { useState, useEffect, useReducer } from "react";
import "./App.css";
import DisplayUser from "./comp/DisplayUser";
const initialState = {
firstStep: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { firstStep: state.firstStep + action.payload };
case "decrement":
return { firstStep: state.firstStep - action.payload };
case "reset":
return initialState;
default:
return state;
}
};
export const UserContext = React.createContext();
function App() {
const [count, setCount] = useState(0);
const [tick, setTick] = useState(0);
const [step, dispatch] = useReducer(reducer, initialState);
const increaseCount = () => {
setCount((prevCount) => prevCount + 1);
};
const decreaseCount = () => {
console.log("De");
setCount((prevCount) => prevCount - 1);
};
useEffect(() => {
setTimeout(() => {
setTick((prevCount) => prevCount + 1);
}, 1000);
}, [tick]);
return (
<div className="App">
<section className="AppUseState">
<h2>useState</h2>
<article>
<h4>Count : {count}</h4>
<button onClick={() => increaseCount()}>Tick Plus</button>
<button onClick={() => decreaseCount()}>Tick Minus</button>
</article>
</section>
<section className="AppUseEffect">
<h2>useEffect</h2>
<article>
<h4>Tick : {tick}</h4>
</article>
</section>
<section className="AppUseReducer">
<h2>useReducer</h2>
<article>
<h4>Step : {step.firstStep}</h4>
<button onClick={() => dispatch({ type: "increment", payload: 5 })}>
Tick Plus
</button>
<button onClick={() => dispatch({ type: "decrement", payload: 3 })}>
Tick Minus
</button>
</article>
</section>
<section className="AppUseContext">
<h2>useContext</h2>
<article>
<UserContext.Provider value={{ userName: "Mohit" }}>
<DisplayUser />
</UserContext.Provider>
</article>
</section>
</div>
);
}
export default App;
每当 setTimeout 中的 setTick 方法运行时,它基本上都会重新渲染 DisplayUser 组件。(我在 DisplayUser 组件中有一个控制台日志)。我的 DisplayUser 组件看起来像这样
import React, { useContext } from "react";
import { UserContext } from "../App";
function DisplayUser() {
const user = useContext(UserContext);
console.log(user);
return (
<React.Fragment>
<p>Hello from {user.userName}</p>
</React.Fragment>
);
}
export default DisplayUser;
有人可以向我解释为什么 useEffect 基本上是重新渲染我的上下文 api 消费者组件的这种行为吗?