LoginSignup
0
0

More than 1 year has passed since last update.

【Redux】Redux Toolkitを使ってみた

Last updated at Posted at 2022-06-19

コンポーネントにどこからでもアクセス!

Reduxを利用している場合はindex.jsのProviderで包んでいるコンポーネント以下にあるコンポーネントからであればどこからでもアクセスすることができます。その時にはuseSelector Hookでアクセスを行い、useDispatch Hookを利用して更新を行います。

参考にさせていただいた記事

コード

public>index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
src>index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { store } from './redux/store';
import { Provider } from 'react-redux';

ReactDOM.render(
  // index.js(親)→store.js(子)?
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
src>App.js
import './App.css';
import { useSelector,useDispatch } from 'react-redux';
import {decrease,increase} from './redux/counterSlice';

function App() {
  const count = useSelector((state) => state.counter.count);
  const dispatch =useDispatch();
  return (
    <div className="App">
      <h1>Count: {count}</h1>
      <button onClick={()=>dispatch(increase())}>Up</button>
      <button onClick={()=>dispatch(decrease())}>Down</button>
    </div>
  );
}

export default App;
src>redux>store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
});
src>redux>counterSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    count: 100,
  },
  reducers: {
    increase: (state) => {
      state.count += 1;
    },
    decrease: (state) => {
      state.count -= 1;
    },
  },
});

export const { increase, decrease } = counterSlice.actions;
export default counterSlice.reducer;

ファイルの関係性

image.png

疑問

  • store.jsの役割?
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0