整合以下連結內的教學建立一個專案:
1.[Webpack 4
Tutorial: from 0 Conf to Production Mode]
2.[React Redux
Tutorial for Beginners: learning Redux in 2018]
3.[React Router
v4 官方文件: Quick Start ]
4.[Redux Async
Actions - Redux Tutorial #6]
安裝:
$
npm install --save-dev webpack webpack-cli
webpack-dev-server babel-core babel-loader babel-preset-env babel-preset-react
babel-plugin-transform-object-rest-spread html-webpack-plugin html-loader
$
npm install --save react react-dom react-router-dom
prop-types redux react-redux redux-thunk redux-promise-middleware redux-logger axios
配置:
webpack.config.js
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'inline-source-map',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
filename: './index.html'
})
]
};
.babelrc
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}
package.json的script
"scripts": {
"start": "webpack-dev-server
--mode development --open",
"build": "webpack
--mode production"
},
專案結構:
[src]
[js]
[actions]
[components]
[constants]
[reducers]
[store]
index.js
index.html
備註:
想關掉webpack server時按下Ctrl+C,但是還是在running,要真的停止必須執行:
taskkill /F /IM node.exe
Redux 的 Middleware 套件說明:
1.
redux的dispatch只接受plain object,可使用redux-thunk來讓dispatch也可以接受function
2.
使用redux-promise-middleware可以讓action.payload為Promise類型來達到簡化設計三種狀態:Penging, Fulfilled, Rejected
3.
redux-promise-middleware可以和redux-thunk結合起來鍊接action
範例:使用者登入後取得他的文章
const mapDispatchToProps = dispatch => {
return {
login: (email, password) => dispatch(login(email, password))
};
};
export const login = (email, password) => dispatch => {
dispatch({
type: 'LOGIN',
payload: axios.post('http://localhost:5000/api/Token', {
email,
password
})
}).then(reponse => {
dispatch({
type: 'FETCH_POSTS',
payload: axios.get('http://localhost:5000/api/posts')
});
});
};
沒有留言:
張貼留言