Created
August 14, 2019 11:18
-
-
Save hacker0limbo/fe7244bd456765c936aabef0ff15b015 to your computer and use it in GitHub Desktop.
use useReducer and useRef hooks to create a counter and todo example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useReducer, useRef } from 'react' | |
| import ReactDOM from 'react-dom' | |
| const Counter = () => { | |
| const [count, dispatch] = useReducer((state, action) => { | |
| switch(action) { | |
| case 'INCREMENT': | |
| return state + 1 | |
| case 'DECREMENT': | |
| return state - 1 | |
| default: | |
| return state | |
| } | |
| }, 0) | |
| return ( | |
| <div> | |
| {count} | |
| <button onClick={() => dispatch('INCREMENT')}>+</button> | |
| <button onClick={() => dispatch('DECREMENT')}>-</button> | |
| </div> | |
| ) | |
| } | |
| const Todo = () => { | |
| const inputRef = useRef() | |
| const [todos, dispatch] = useReducer((state, action) => { | |
| switch(action.type) { | |
| case 'ADD': | |
| return [ | |
| ...state, | |
| { id: state.length, name: action.name } | |
| ] | |
| case 'REMOVE': | |
| return state.filter((_, index) => index !== action.index) | |
| case 'CLEAR': | |
| return [] | |
| default: | |
| return state | |
| } | |
| }, []) | |
| const handleSubmit = (e) => { | |
| e.preventDefault() | |
| // 传递 type 和 数据 | |
| dispatch({ | |
| type: 'ADD', | |
| name: inputRef.current.value | |
| }) | |
| inputRef.current.value = '' | |
| } | |
| return ( | |
| <div> | |
| <form onSubmit={handleSubmit}> | |
| <input ref={inputRef} /> | |
| </form> | |
| <button onClick={ () => dispatch({ type: 'CLEAR' }) }>Clear</button> | |
| <ul> | |
| {todos.map((todo, index) => ( | |
| <li key={todo.id}> | |
| {todo.name} | |
| <button onClick={() => dispatch({ type: 'REMOVE', index })}>X</button> | |
| </li> | |
| ))} | |
| </ul> | |
| </div> | |
| ) | |
| } | |
| const App = () => { | |
| return ( | |
| <div id="app"> | |
| <Counter /> | |
| <Todo /> | |
| </div> | |
| ) | |
| } | |
| const rootElement = document.getElementById("root") | |
| ReactDOM.render(<App />, rootElement) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment