「Javascript/react/redux」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→動作) |
|||
行90: | 行90: | ||
npm start | npm start | ||
</pre> | </pre> | ||
− | ブラウザで、localhost: | + | ブラウザで、localhost:3000を開くと、カウンタのup,downは、動いてた。 |
==参考== | ==参考== | ||
https://gizanbeak.com/post/react-redux-tutorial | https://gizanbeak.com/post/react-redux-tutorial |
2024年6月4日 (火) 06:52時点における最新版
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
動作
npm start
ブラウザで、localhost:3000を開くと、カウンタのup,downは、動いてた。