第一手尝试 React Hook 的 useReducer

第一手尝试 React Hook 的 useReducer:


import React, {useState,useEffect,useReducer} from 'react';
import ReactDOM from 'react-dom';


let histories = [];


const initialState = {
	counter: 10
}

const reducer = function(state,action){
	switch(action.type){
		case('INCREMENT'):
			return {...state, counter: state.counter + 1};
		case('DECREMENT'):
			return {...state, counter: state.counter - 1};
		default:
			throw new Error();
	}
}


const App = function(props){
	
	let _style = {
		textAlign: 'center',
		margin: '100px',
		fontSize: '50px',
		lineHeight: '100px'
	}
	
	const [state,dispatch] = useReducer(reducer,initialState);
	
	useEffect(() => {
		histories.push(state.counter);
		console.log(histories);
	},[state.counter]);
	
	return (
		<>
			<div style={_style}>
				{state.counter}
				<br />
				<button onClick={() => {dispatch({type:'INCREMENT'})}}>Increment</button>
				<button>Just Kidding</button>
				<button onClick={() => {dispatch({type:'DECREMENT'})}}>Decrement</button>
			</div>
		</>
	)
}


ReactDOM.render(
	<App />
	,
	document.getElementById('root')
);

Output:


[10]
main.js:24870 (2) [10, 11]
main.js:24870 (3) [10, 11, 12]
main.js:24870 (4) [10, 11, 12, 13]
main.js:24870 (5) [10, 11, 12, 13, 14]
main.js:24870 (6) [10, 11, 12, 13, 14, 15]
main.js:24870 (7) [10, 11, 12, 13, 14, 15, 16]
main.js:24870 (8) [10, 11, 12, 13, 14, 15, 16, 15]
main.js:24870 (9) [10, 11, 12, 13, 14, 15, 16, 15, 14]
main.js:24870 (10) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13]
main.js:24870 (11) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13, 12]
main.js:24870 (12) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13, 12, 11]
main.js:24870 (13) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13, 12, 11, 10]
main.js:24870 (14) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13, 12, 11, 10, 11]
main.js:24870 (15) [10, 11, 12, 13, 14, 15, 16, 15, 14, 13, 12, 11, 10, 11, 12]