我正在尝试理解和练习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消费者组件?