React Hook useReducer
import React, { useReducer } from "react";
import "./App.css";
function FunctComponent(props) {
const initialState = {count: 0, count2:0};
function reducer(state, action){
switch(action.type) {
case 'increment': return {...state,count: state.count + 1};
case 'decrement': return {...state,count: state.count - 1};
case 'incrementc2': return {...state,count2: state.count2 + 1};
default: throw new Error();
}
}
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h3>Function Component using useReducer</h3>
<p>count: {state.count} count2: {state.count2} props: {props.prop1value}</p>
<button onClick={() => dispatch({type: 'increment'}) }>count +</button>
<button onClick={() => dispatch({type: 'decrement'}) }>count -</button>
<button onClick={() => dispatch({type: 'incrementc2'})}>count2 +</button>
</div>
);
}
function App() {
return (
<div className="App">
<FunctComponent prop1="prop1value" />
</div>
);
}
export default App;
browser output:
eot
No hay comentarios:
Publicar un comentario