搭建基本的react項(xiàng)目
- 我們使用create-react-app(npm要全局安裝create-react-app)快速創(chuàng)建一個(gè)react項(xiàng)目:
npx create-react-app my-app
cd my-app
npm start
啟動(dòng)成功后,就可以看到react的頁(yè)面啦犀变。接下來(lái)我們稍稍調(diào)整下項(xiàng)目的目錄結(jié)構(gòu)和頁(yè)面內(nèi)容,新增About頁(yè)面姜挺。
-
在src目錄下新建pages目錄惫叛,用來(lái)放置前端頁(yè)面昌阿。新建App目錄殖告,將原來(lái)App.js和App.css移動(dòng)進(jìn)去烘挫,注意這兩個(gè)文件引入路徑的修改诀艰。
在src目錄下新增Home頁(yè)面和About頁(yè)面(后面用到)
// 路徑:/src/pages/Home/Home.js
import React from 'react'
const Home = () => (
<div>
<h1>Home Page</h1>
<p>這是Home頁(yè)面</p>
</div>
)
export default Home
// 路徑:/src/pages/About/About.js
import React from 'react'
const About = () => (
<div>
<h1>About Page</h1>
<p>這是About頁(yè)面</p>
</div>
)
export default About
接入react-router
接下來(lái),我們開始在項(xiàng)目中接入react-router饮六,通過(guò)npm指令安裝"react-router"和"react-router-dom":
npm i -S react-router react-router-dom
- 我們修改一下
/src/pages/App/App.js
和/src/index.js
的內(nèi)容:
// /src/pages/App/App.js
import React from 'react'
import { Route, Link } from 'react-router-dom'
import Home from '../Home/Home'
import About from '../About/About'
const App = () => (
<div>
<header>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
</header>
<main>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
</main>
</div>
)
export default App
// /src/index.js
// ...省略代碼
import { Router } from "react-router";
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
// ...省略代碼
<Router history={history}>
<App />
</Router>
// ...省略代碼
- 這樣我們就配置好了react-router其垄,執(zhí)行
npm start
命令,在瀏覽器中查看頁(yè)面卤橄,點(diǎn)擊Home展示Home頁(yè)面绿满,點(diǎn)擊About展示About頁(yè)面
接入redux
接下來(lái),我們?cè)陧?xiàng)目中接入redux窟扑,首先通過(guò)npm安裝以下依賴:
npm i react-redux redux redux-thunk connected-react-router
- 在src目錄下新建modules目錄喇颁,這個(gè)目錄用來(lái)存放reducer相關(guān)的文件漏健,新建counter.js和index.js
// /src/modules/counter.js
export const INCREMENT_REQUESTED = 'counter/INCREMENT_REQUESTED'
export const INCREMENT = 'counter/INCREMENT'
export const DECREMENT_REQUESTED = 'counter/DECREMENT_REQUESTED'
export const DECREMENT = 'counter/DECREMENT'
const initialState = {
count: 0,
isIncrementing: false,
isDecrementing: false
}
export default (state = initialState, action) => {
switch (action.type) {
case INCREMENT_REQUESTED:
return {
...state,
isIncrementing: true
}
case INCREMENT:
return {
...state,
count: state.count + 1,
isIncrementing: !state.isIncrementing
}
case DECREMENT_REQUESTED:
return {
...state,
isDecrementing: true
}
case DECREMENT:
return {
...state,
count: state.count - 1,
isDecrementing: !state.isDecrementing
}
default:
return state
}
}
export const increment = () => {
return dispatch => {
dispatch({
type: INCREMENT_REQUESTED
})
dispatch({
type: INCREMENT
})
}
}
export const incrementAsync = () => {
return dispatch => {
dispatch({
type: INCREMENT_REQUESTED
})
return setTimeout(() => {
dispatch({
type: INCREMENT
})
}, 3000)
}
}
export const decrement = () => {
return dispatch => {
dispatch({
type: DECREMENT_REQUESTED
})
dispatch({
type: DECREMENT
})
}
}
export const decrementAsync = () => {
return dispatch => {
dispatch({
type: DECREMENT_REQUESTED
})
return setTimeout(() => {
dispatch({
type: DECREMENT
})
}, 3000)
}
}
// /src/modules/index.js
import { combineReducers } from 'redux'
import counter from './counter'
import { connectRouter } from 'connected-react-router'
const createRootReducer = (history)=> combineReducers({
counter,
router: connectRouter(history)})
export default createRootReducer
- 在src目錄下新建store.js
// /src/store.js
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'connected-react-router'
import thunk from 'redux-thunk'
import * as History from 'history'
import createRootReducer from './modules'
export const history = History.createBrowserHistory()
const initialState = {}
const enhancers = []
const middleware = [thunk, routerMiddleware(history)]
if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION__
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
)
export default createStore(
createRootReducer(history),
initialState,
composedEnhancers
)
- 修改下
/src/index.js
的內(nèi)容:
// /src/index.js
// ...省略代碼
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'connected-react-router'
import store, { history } from './store'
// ...省略代碼
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>
// ...省略代碼
- 在Home頁(yè)和About頁(yè)中接入redux
// 修改 /src/pages/Home/Home.js
import React from 'react'
import { push } from 'connected-react-router'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import {
increment,
incrementAsync,
decrement,
decrementAsync
} from '../../modules/counter'
const Home = props => (
<div>
<h1>Home</h1>
<p>Count: {props.count}</p>
<p>
<button onClick={props.increment}>Increment</button>
<button onClick={props.incrementAsync} disabled={props.isIncrementing}>
Increment Async
</button>
</p>
<p>
<button onClick={props.decrement}>Decrement</button>
<button onClick={props.decrementAsync} disabled={props.isDecrementing}>
Decrement Async
</button>
</p>
<p>
<button onClick={() => props.changePage()}>
Go to about page via redux
</button>
</p>
</div>
)
const mapStateToProps = ({ counter }) => ({
count: counter.count,
isIncrementing: counter.isIncrementing,
isDecrementing: counter.isDecrementing
})
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
increment,
incrementAsync,
decrement,
decrementAsync,
changePage: () => push('/about')
},
dispatch
)
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home)
// 修改 /src/pages/About/About.js
import React from 'react'
import { connect } from 'react-redux'
const About = (props) => (
<div>
<h1>About Page</h1>
<p>這是About頁(yè)面</p>
<p>count計(jì)數(shù):{props.count}</p>
</div>
)
const mapStateToProps = ({ counter }) => ({
count: counter.count
})
export default connect(
mapStateToProps
)(About)
- 到此,一個(gè)react+react-router+redux的基本項(xiàng)目就已經(jīng)配置完成了橘霎,接下來(lái)就可以做更深層次的業(yè)務(wù)開發(fā)了蔫浆。
結(jié)尾
本文中沒(méi)有對(duì)react-router和redux做什么原理性和概念性的介紹,純粹作為傻瓜式的教程茎毁,由react基本項(xiàng)目克懊,到接入react-router忱辅,最后接入redux完成一個(gè)基本的react全家桶項(xiàng)目搭建七蜘,目的是讓初學(xué)者能夠體驗(yàn)一下完整的react全家桶基本項(xiàng)目。在本教程中如果有什么問(wèn)題墙懂,可以留言哦橡卤。
如果想要深入理解react、react-router和redux的知識(shí)损搬,建議去官網(wǎng)閱讀文檔深入學(xué)習(xí)碧库。
最后,在業(yè)余時(shí)間編寫了一個(gè)快速構(gòu)建react全家桶項(xiàng)目模板巧勤、vue2.x全家桶項(xiàng)目模板和嵌灰、vue3項(xiàng)目模板的npm腳手架fast-project,希望大家能夠下載體驗(yàn)颅悉,給出一些建議吶~
番外
之前的教程是搭建一個(gè)常見jsx版react項(xiàng)目沽瞭,最近在新項(xiàng)目中使用了ts語(yǔ)言,組件編寫全面擁抱了hooks剩瓶,redux使用reduxjs/toolkit驹溃,而不是thunk。新的項(xiàng)目模板地址https://gitee.com/duchengdong/react-ts-template.git延曙,同時(shí)也已經(jīng)添加到了fast-project快速搭建項(xiàng)目腳手架里豌鹤。