模板之React项目框架搭建

创建React项目

1. 创建项目

npx create-react-app demo(项目名称)
cd demo

2. 下载依赖

npm i antd node-sass --save

使用react-redux

1. 下载依赖

npm install redux react-redux redux-saga redux-devtools js-base64 --save

2. 目录结构

在这里插入图片描述

3. store

index.js

// createStore 创建store对象,保存state
// applyMiddleware 使用中间件
// compose 从右到左组合函数
import { createStore, applyMiddleware, compose } from "redux";
// createSagaMiddleware 创建saga对象
import createSagaMiddleware from 'redux-saga';
import { Base64 } from 'js-base64';
import reducers from './reducers';
import rootSaga from "./sagas";

const sagaMiddleware = createSagaMiddleware();

// 扩展浏览器工具
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

// store 的默认值
let defaultState = {
  userInfo: {}
}

const localRedux = window.sessionStorage.getItem('redux');
if (localRedux) {
  defaultState = JSON.parse(Base64.decode(localRedux));
}

export default createStore(
  reducers,
  defaultState,
  composeEnhancers(
    applyMiddleware(sagaMiddleware)
  )
)

sagaMiddleware.run(rootSaga);

actions

action-type.js

定义动作类型常量,可以根据实际需要来确定是否使用这个文件,如果是大型项目,建议使用。

export const LOGIN = 'LOGIN';
export const TEST1 = 'TEST1';
export const TEST2 = 'TEST2';
export const SAVA_USER_INFO = 'SAVA_USER_INFO';
index.js
import { SAVA_USER_INFO } from './action-type';

// 保存用户信息
export const saveUserInfo = (payload) => {
  return {
    type: SAVA_USER_INFO,
    payload
  }
}

reducers

index.js
import { combineReducers } from "redux";
import userInfo from "./userInfo";

export default combineReducers({
  userInfo
});
userInfo.js
import { SAVA_USER_INFO } from '../actions/action-type';

export default function(state={}, actions) {
  switch (actions.type) {
    case SAVA_USER_INFO: {
      return actions.payload;
    }
    default: {
      return state;
    }
  }
}

saga

index.js

redux-saga 可以处理异步操作。

import { all } from 'redux-saga/effects';
import loginSaga from './loginSaga';
import testSaga from "./testSaga";

export default function* rootSaga() {
  yield all([
    loginSaga,
    testSaga
  ])
}
loginSaga.js
import { put, call, takeEvery } from 'redux-saga/effects';
import { LOGIN } from "../actions/action-type";

function* login(actions) {
  console.log('loginSaga:', actions);
}

export default function* () {
  yield takeEvery(LOGIN, login);
}
testSaga.js
import { put, call, takeEvery } from 'redux-saga/effects';
import { TEST1, TEST2 } from "../actions/action-type";

function* test1(actions) {
  console.log('test1Saga:', actions);
}

function* test2(actions) {
  console.log('test2Saga:', actions);
}

export default function* () {
  yield takeEvery(TEST1, test1);
  yield takeEvery(TEST2, test2);
}

4. 项目引入store

4.1 根组件挂载store

src/ index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from "react-redux";
import './index.scss';
import App from './components/App';
import store from './redux';

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

4.2 组件中使用store

以App组件为例。

App/index.jsx

容器组件

import { connect } from "react-redux";
import App from './App';
import { saveUserInfo } from "../../redux/actions";

function mapStateToProps(state, ownerProps={}) {
  return {
    ...state,
    ...ownerProps
  }
}

function mapDispatchToProps(dispatch) {
  return {
    saveUserInfo: (userInfo = {}) => {
      dispatch(saveUserInfo(userInfo));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)
App/App.jsx

功能组件

import React, { Component } from "react";
import { Button } from "antd";
import { Base64 } from "js-base64";
import './index.scss';


class App extends Component {

  componentDidMount() {
    window.addEventListener('beforeunload', this.handleBeforeUnload);
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.handleBeforeUnload);
  }

  handleBeforeUnload = () => {
    const { userInfo } = this.props;
    window.sessionStorage.setItem('redux', Base64.encode(JSON.stringify({ userInfo })))
  }

  render() {
    return (
      <div className="App">
        App Component
        <Button onClick={() => this.props.saveUserInfo({name: 'gaoli'})}>
        	保存用户信息
        </Button>
      </div>
    );
  }
}

export default App;

使用react-router

1. 下载依赖文件

npm i react-router-dom --save

2. src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from "react-redux";
import { BrowserRouter } from 'react-router-dom';
import './index.scss';
import App from './components/App';
import TestRouter from './components/TestRouter';
import store from './redux';

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

文档地址

  1. redux: https://www.redux.org.cn/
  2. redux-saga: https://redux-saga-in-chinese.js.org/
  3. js-base64: https://www.npmjs.com/package/js-base64
  4. react-router: http://react-router.docschina.org/
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值