Created
January 23, 2022 04:07
-
-
Save ynwd/b2edeada584d81d9291e988be1788413 to your computer and use it in GitHub Desktop.
react redux example
This file contains 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 from 'react' | |
import { Provider, useSelector, useDispatch } from 'react-redux' | |
import { createStore } from 'redux' | |
function Counter() { | |
const count = useSelector(state => state.count) | |
const dispatch = useDispatch() | |
const action = { | |
type: "ADD", | |
count: 1 | |
} | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => dispatch(action)}> | |
Click me | |
</button> | |
</div> | |
) | |
} | |
const defaultCount = { | |
count: 0 | |
} | |
function reducer(state = defaultCount, action) { | |
if (action.type === "ADD") { | |
return { | |
count: state.count + 1 | |
} | |
} | |
return { | |
count: 0 | |
} | |
} | |
const store = createStore(reducer) | |
function App() { | |
return ( | |
<Provider store={store}> | |
<Counter /> | |
</Provider> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment