Javascript/react/redux
提供: 初心者エンジニアの簡易メモ
reduxを使ったプロジェクト作成
npx create-react-app helloredux cd helloredux npm install redux react-redux
追加js
src/reducers/counter.js
const initialState = {
count: 0
}
const counter = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 }
case 'DECREMENT':
return { ...state, count: state.count - 1 }
default:
return state
}
}
export default counter
src/store.js
import { createStore } from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)
export default store
src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import store from './store'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<App />
</Provider>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
src/App.js
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
function App() {
const count = useSelector((state) => state.count)
const dispatch = useDispatch()
const increment = () => dispatch({ type: 'INCREMENT' })
const decrement = () => dispatch({ type: 'DECREMENT' })
return (
<div>
<h1>カウント: {count}</h1>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
</div>
)
}
export default App
