JavaScript
React
redux
react-redux

ReduxのサンプルのTodoリストを真似てみる。Part.1

More than 1 year has passed since last update.

Redux ExampleのTodo Listをはじめからていねいに(1)を参考にさせて頂いて、Reduxのコードを書いた。


0.留意点


  • 初心者の覚書です。

  • 自分の環境で動くように参考にしたコードを適当に修正している。

  • Windows10 64bit , PowerShellなどで動かしている。

  • 見栄えを若干よくする為にbootstrap4を利用している。


1.PowerShellで環境準備


PowerShell

PS C:\Users\Taro\Desktop> mkdir ws

ディレクトリ: C:\Users\Taro\Desktop

Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2018/05/27 14:26 ws

PS C:\Users\Taro\Desktop> cd ws
PS C:\Users\Taro\Desktop\ws> npm init -y
Wrote to C:\Users\Taro\Desktop\ws\package.json:

{
"name": "ws",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

PS C:\Users\Taro\Desktop\ws> npm i -D babel-core babel-loader babel-preset-env babel-preset-react
npm notice created a lockfile as package-lock.json. You should commit this file. es-commonjs
npm WARN babel-loader@7.1.4 requires a peer of webpack@2 || 3 || 4 but none is installed. You must install peer dependencies yourself.
npm WARN ws@1.0.0 No description
npm WARN ws@1.0.0 No repository field.

+ babel-preset-env@1.7.0
+ babel-core@6.26.3
+ babel-preset-react@6.24.1
+ babel-loader@7.1.4
added 128 packages from 67 contributors in 9.211s
[+] no known vulnerabilities found [2032 packages audited]

PS C:\Users\Taro\Desktop\ws> npm i -D webpack webpack-cli webpack-dev-server
npm WARN deprecated nomnom@1.8.1: Package no longer supported. Contact support@npmjs.com for more info.
npm WARN deprecated babel-preset-es2015@6.24.1: 🙌 Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!
npm WARN ws@1.0.0 No description es\extend-shallow
npm WARN ws@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ webpack-cli@2.1.4
+ webpack@4.9.1
+ webpack-dev-server@3.1.4
added 805 packages from 507 contributors in 29.534s
[+] no known vulnerabilities found [17167 packages audited]

PS C:\Users\Taro\Desktop\ws> npm install --save react react-dom redux react-redux prop-types
npm WARN ws@1.0.0 No description ments
npm WARN ws@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.4 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.4: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ react-redux@5.0.7
+ react-dom@16.4.0
+ redux@4.0.0
+ prop-types@15.6.1
+ react@16.4.0
added 17 packages from 86 contributors in 5.909s
[+] no known vulnerabilities found [17300 packages audited]

PS C:\Users\Taro\Desktop\ws> ni .babelrc , webpack.config.js, index.html

ディレクトリ: C:\Users\Taro\Desktop\ws

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018/05/27 14:28 0 .babelrc
-a---- 2018/05/27 14:28 0 webpack.config.js
-a---- 2018/05/27 14:28 0 index.html

PS C:\Users\Taro\Desktop\ws> mkdir src, dist

ディレクトリ: C:\Users\Taro\Desktop\ws

Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2018/05/27 14:29 src
d----- 2018/05/27 14:29 dist

PS C:\Users\Taro\Desktop\ws> cd src
PS C:\Users\Taro\Desktop\ws\src> mkdir actions, components, containers, reducers

ディレクトリ: C:\Users\Taro\Desktop\ws\src

Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2018/05/27 14:29 actions
d----- 2018/05/27 14:29 components
d----- 2018/05/27 14:29 containers
d----- 2018/05/27 14:29 reducers

PS C:\Users\Taro\Desktop\ws\src> cd ..
PS C:\Users\Taro\Desktop\ws> code .



2.プロジェクトの設定ファイルを編集


.bashrc

{

"presets": [
"env","react"
]
}


package.json

{

"name": "ws",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --progress",
"start": "webpack-dev-server --watch --progress"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"webpack": "^4.9.1",
"webpack-cli": "^2.1.4",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"prop-types": "^15.6.1",
"react": "^16.4.0",
"react-dom": "^16.4.0",
"react-redux": "^5.0.7",
"redux": "^4.0.0"
}
}



webpack.config.js

const path = require('path');

module.exports = {
mode:'development',
entry: './src/index.js',
output: {
path: path.join(__dirname,'dist'),
filename: 'index.js',
publicPath: path.join(__dirname,'dist')
},
devtool: '#source-map',
devServer: {
contentBase: './',
port: 8080
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
]
}
};



3.ファイルを大まかに作成


プロジェクトディレクトリ/index.html

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title>ReduxでTodoリストを作ろう</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div id="root"></div>
<script src="dist/index.js"></script>
</body>
</html>


components/App.js

import React from 'react';

const App = ()=>(
<h1>ダミーH1</h1>
)

export default App;



reducers/index.js

const reducers =  (state,action)=>{

return state;
}
export default reducers;


./index.js

import React from 'react';

import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import reducers from './reducers'
import { createStore } from 'redux';
import App from './components/App'

let store = createStore(reducers);

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);



コマンド実行

npm run build

npm run start

http://localhost:8080で動作確認

ソースコード 01


3.stateをTodo用に加工し、コンソールで確認


actionCreatorをつくる

actionを作る関数


actions/index.js

let nextTodoId=0

const addTodo= (text)=>{
return{
type:'ADD_TODO',
id:nextTodoId++,
text

}
}
export default addTodo;



reducersを修正

actionとstateを引数にとり、なかでアプリケーションのロジックを駆使して新しいstateを返す関数をつくる。名前もreducersからtodoに変更している。


reducers/index.js

const todo = (state, action) => {

switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text
}
default:
return state;
}
}
export default todo;

index.jsを修正


index.js

import React from 'react';

import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import todo from './reducers'
import { createStore } from 'redux';
import App from './components/App'
import addTodo from './actions'

let store = createStore(todo);
store.dispatch(addTodo('Todo 1番目'));
console.log(store.getState());

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);


http://localhost:8080で動作確認。コンソールにstateが出てくればOK

ソースコード 02


追記

編集リクエストで シンタックスハイライトのところ、JavaScript->jsxして頂いた方、ありがとうございます。2018/05/28 16:31