Skip to main content

一步步,带你体验全栈开发(五)

· 2 min read
bigBlack

目标:React常用Hook及概念练习

在这个练习中,我们将通过一步步的实践,熟悉React中常用的Hook和一些重要的概念。

第一步,useState Hook

使用useState Hook来实现组件状态的管理。

import React, { useState } from 'react';

const Counter = () => {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

export default Counter;

第二步,useEffect Hook

使用useEffect Hook来处理副作用,例如数据获取、订阅等。

import React, { useState, useEffect } from 'react';

const DataFetching = () => {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/todos')
.then((response) => response.json())
.then((data) => setData(data));
}, []);

return (
<div>
<h2>Data Fetching</h2>
<ul>
{data.map((item) => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
};

export default DataFetching;

第三步,useContext Hook

使用useContext Hook来访问React的上下文。

import React, { useContext } from 'react';

const ThemeContext = React.createContext();

const ThemedComponent = () => {
const theme = useContext(ThemeContext);

return (
<div style={{ color: theme === 'dark' ? 'white' : 'black' }}>
Themed Component
</div>
);
};

export const App = () => {
return (
<ThemeContext.Provider value="dark">
<ThemedComponent />
</ThemeContext.Provider>
);
};

第四步,useReducer Hook

使用useReducer Hook来管理复杂的状态逻辑。

import React, { useReducer } from 'react';

const initialState = { count: 0 };

const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};

const CounterWithReducer = () => {
const [state, dispatch] = useReducer(reducer, initialState);

return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
};

export default CounterWithReducer;

第五步,自定义Hook

创建自定义Hook来提取和重用组件逻辑。

import { useState, useEffect } from 'react';

const useDataFetching = (url) => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
setLoading(true);
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
});
}, [url]);

return { data, loading };
};

export default useDataFetching;

总结

通过这个React常用Hook及概念的练习,我们熟悉了useStateuseEffectuseContextuseReducer等React Hook,以及自定义Hook的使用。这些Hook能够使我们更轻松地管理组件的状态和副作用,提高代码的可维护性和可重用性。

希望这个练习能够帮助你更深入地理解和应用React中的Hook。