useReducer
반응 16.8에 도입 된 반응 후크입니다. 감속기 기능을 사용하여 상태를 업데이트하여보다 복잡한 상태 로직을 관리하는 데 특히 유용합니다. 감속기 함수는 현재 상태와 동작을 인수로 취하고 동작 유형에 따라 새 상태를 반환합니다. 이 접근법은 인기있는 주 관리 라이브러리 인 Redux에서 영감을 얻었으며 주 업데이트를 구성하고 예측할 수 있도록 도와줍니다.
useReducer
의 구문은 다음과 같습니다.
<code class="javascript">const [state, dispatch] = useReducer(reducer, initialArg, init);</code>
init
통과하여 초기 상태를 게으르게 생성 할 수도 있습니다.initialArg
로 한 번 호출됩니다. useReducer
사용하면 다음을 포함하여 복잡한 상태를 관리 할 때 useState
보다 몇 가지 이점이 있습니다.
useReducer
사용하면 상태 업데이트 로직을 구성 요소와 분리하여 테스트 및 유지 관리를보다 쉽게 할 수 있습니다. 감속기 함수는 상태가 어떻게 변하는 지 설명하는 순수한 기능이며, 필요한 경우 자체 파일로 분리 할 수 있습니다.useReducer
빛납니다. 상태 업데이트를 더 작고 관리하기 쉬운 작업 유형으로 분류 할 수 있습니다.useReducer
can be used with useCallback
to memoize the dispatch function, potentially improving performance.useReducer
pairs well with useContext
for managing global state, allowing for a more scalable state management solution across multiple components. While useReducer
itself doesn't handle side effects directly, it can be paired with useEffect
to manage side effects based on state changes effectively. useReducer
부작용을 촉진하는 방법은 다음과 같습니다.
useReducer
사용하여 상태를 관리하면 모든 상태 전환을 한 곳에서 정의 할 수 있습니다. 따라서 어떤 상태 변경이 부작용을 유발할 수 있는지 이해하기가 더 쉽습니다.useReducer
ensures predictable state updates, you can depend on these updates to trigger side effects in a consistent manner. useEffect
후크를 설정하여 특정 상태 변경을 듣고 그에 따라 부작용을 실행할 수 있습니다.useEffect
후크 내의 useReducer
반환 한 상태를 사용하여 부작용을 트리거 할 수 있습니다. For example, if the state change involves fetching data, you can dispatch an action to update the state, and a useEffect
hook can respond to this state change by making an API call.기본 예는 다음과 같습니다.
<code class="javascript">const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { if (state.fetchData) { // Fetch data here fetchData().then(data => dispatch({ type: 'dataFetched', payload: data })); } }, [state.fetchData]);</code>
In this example, when state.fetchData
becomes true, the useEffect
hook triggers a data fetch, and once the data is fetched, it dispatches another action to update the state with the fetched data.
RECT 구성 요소에서 useReducer
의 실제 구현을 보여주기 위해 간단한 TODO 목록 응용 프로그램을 작성하겠습니다.
먼저, 우리는 감속기와 초기 상태를 정의합니다.
<code class="javascript">// Reducer const todoReducer = (state, action) => { switch (action.type) { case 'ADD_TODO': return { ...state, todos: [...state.todos, { id: Date.now(), text: action.payload, completed: false }] }; case 'TOGGLE_TODO': return { ...state, todos: state.todos.map(todo => todo.id === action.payload ? { ...todo, completed: !todo.completed } : todo ) }; case 'REMOVE_TODO': return { ...state, todos: state.todos.filter(todo => todo.id !== action.payload) }; default: return state; } }; // Initial state const initialState = { todos: [] };</code>
이제 useReducer
사용하는 TodoList
구성 요소를 만들어 봅시다.
<code class="jsx">import React, { useReducer } from 'react'; const TodoList = () => { const [state, dispatch] = useReducer(todoReducer, initialState); const handleAddTodo = (text) => { dispatch({ type: 'ADD_TODO', payload: text }); }; const handleToggleTodo = (id) => { dispatch({ type: 'TOGGLE_TODO', payload: id }); }; const handleRemoveTodo = (id) => { dispatch({ type: 'REMOVE_TODO', payload: id }); }; return ( <div> <h1>Todo List</h1> <input type="text" onkeypress="{(e)"> { if (e.key === 'Enter') { handleAddTodo(e.target.value); e.target.value = ''; } }} placeholder="Enter a new todo" /> <ul> {state.todos.map(todo => ( <li key="{todo.id}"> <span style="{{" textdecoration: todo.completed : onclick="{()"> handleToggleTodo(todo.id)} > {todo.text} </span> <button onclick="{()"> handleRemoveTodo(todo.id)}>Remove</button> </li> ))} </ul> </div> ); }; export default TodoList;</code>
이 예에서는 useReducer
사용하여 TODO 목록의 상태를 관리합니다. todoReducer
함수는 ADD_TODO
, TOGGLE_TODO
및 REMOVE_TODO
세 가지 동작 유형을 처리합니다. dispatch
함수는 retiser에 동작을 보내는 데 사용되며, 그에 따라 상태가 업데이트됩니다. 이 접근법은 상태 논리를 중앙 집중화하고 예측 가능하게 유지하여 구성 요소를 더 쉽게 유지하고 이해할 수 있도록합니다.
위 내용은 usereducer 란 무엇입니까? 복잡한 상태를 관리하는 데 어떻게 사용합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!