搭建基本的react项目
- 我们使用create-react-app(npm要全局安装create-react-app)快速创建一个react项目:
npx create-react-app my-app
cd my-app
npm start
启动成功后,就可以看到react的页面啦。接下来我们稍稍调整下项目的目录结构和页面内容,新增About页面。
-
在src目录下新建pages目录,用来放置前端页面。新建App目录,将原来App.js和App.css移动进去,注意这两个文件引入路径的修改。
在src目录下新增Home页面和About页面(后面用到)
// 路径:/src/pages/Home/Home.js
import React from 'react'
const Home = () => (
Home Page
这是Home页面
)
export default Home
// 路径:/src/pages/About/About.js
import React from 'react'
const About = () => (
About Page
这是About页面
)
export default About
接入react-router
接下来,我们开始在项目中接入react-router,通过npm指令安装"react-router"和"react-router-dom":
npm i -S react-router react-router-dom
- 我们修改一下
/src/pages/App/App.js
和/src/index.js
的内容:
// /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 = () => (
Home
About
)
export default App
// /src/index.js
// ...省略代码
import { Router } from "react-router";
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
// ...省略代码
// ...省略代码
- 这样我们就配置好了react-router,执行
npm start
命令,在浏览器中查看页面,点击Home展示Home页面,点击About展示About页面
接入redux
接下来,我们在项目中接入redux,首先通过npm安装以下依赖:
npm i react-redux redux redux-thunk connected-react-router
- 在src目录下新建modules目录,这个目录用来存放reducer相关的文件,新建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
的内容:
// /src/index.js
// ...省略代码
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'connected-react-router'
import store, { history } from './store'
// ...省略代码
// ...省略代码
- 在Home页和About页中接入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 => (
Home
Count: {props.count}
)
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) => (
About Page
这是About页面
count计数:{props.count}
)
const mapStateToProps = ({ counter }) => ({
count: counter.count
})
export default connect(
mapStateToProps
)(About)
- 到此,一个react+react-router+redux的基本项目就已经配置完成了,接下来就可以做更深层次的业务开发了。
结尾
本文中没有对react-router和redux做什么原理性和概念性的介绍,纯粹作为傻瓜式的教程,由react基本项目,到接入react-router,最后接入redux完成一个基本的react全家桶项目搭建,目的是让初学者能够体验一下完整的react全家桶基本项目。在本教程中如果有什么问题,可以留言哦。
如果想要深入理解react、react-router和redux的知识,建议去官网阅读文档深入学习。
最后,在业余时间编写了一个快速构建react全家桶项目模板、vue2.x全家桶项目模板和、vue3项目模板的npm脚手架fast-project,希望大家能够下载体验,给出一些建议吶~
番外
之前的教程是搭建一个常见jsx版react项目,最近在新项目中使用了ts语言,组件编写全面拥抱了hooks,redux使用reduxjs/toolkit,而不是thunk。新的项目模板地址https://gitee.com/duchengdong/react-ts-template.git,同时也已经添加到了fast-project快速搭建项目脚手架里。