Skip to content

Commit

Permalink
fixed hot-loader bug and replace react-router 4.0
Browse files Browse the repository at this point in the history
  • Loading branch information
aemoe committed Apr 30, 2017
1 parent c49d19a commit 9ade40b
Show file tree
Hide file tree
Showing 24 changed files with 169 additions and 322 deletions.
149 changes: 1 addition & 148 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1157,157 +1157,10 @@ Nodejs端图片验证:https://github.com/trekjs/captcha
<h2 align="center">开发BUG日记</h2>
当开发中遇到的问题,我会列在下面,以方便自己查询和其他人进行相同问题的修改和修复
https://github.com/aemoe/fairy/issues
<h2 align="center">React使用中遇到的相关问题</h2>
**问题**
```
谷歌报错 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component.
```
**原因**
```
原因是未及时清除掉定时器或者变量,造成了报错会造成内存溢出|使用this定义变量,然后用componentWillUnmount()中清除定时器,方法见官方定时器demo,如下:
```
**解决方案**
```js
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {secondsElapsed: 0};
}

tick() {
this.setState((prevState) => ({
secondsElapsed: prevState.secondsElapsed + 1
}));
}

componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}

componentWillUnmount() {
clearInterval(this.interval);
}

render() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
}
ReactDOM.render(<Timer />, mountNode);
```
**问题**
```
谷歌报错 ReactDOMComponentTree.js:113 Uncaught TypeError: Cannot read property '__reactInternalInstance$xvrt44g6a8' of null
at Object.getClosestInstanceFromNode.
Uncaught RangeError: Maximum call stack size exceeded
```
**原因**
```
未知,可能是图片重复使用或者堆栈造成内存溢出和报错
```
**解决方案**
```js
render((
<Provider store={store}>
{routes}
</Provider>
), document.getElementById('root'));
改为
render((
<div>
<Provider store={store}>
{routes}
</Provider>
</div>
), document.getElementById('root'));
```
**问题**
```
引入react-hot-loader3之后报错
Warning: ExceptionsManager.js:76 <Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/reactjs/react-redux/releases/tag/v2.0.0 for the migration instructions.

Warning: [react-router] You cannot change <Router routes>; it will be ignored

```
**原因**
```
第一个问题未知,请参考client/redux的文件夹里面的设置可以解决

react-router3 在使用react-hot-loader3时会出现报错的问题, 不需要管它, 这并不影响使用 如果想解决可以给router加随机数
<Router history={history} routes={routes} key={Math.random()}/>
或者更换react-router4 即可
```
<h2 align="center">NodeJS后端及服务器端遇到的问题</h2>
**问题**
```
如何在后端运行时,忽略css文件,防止nodejs后端服务器报错|node服务器不能正确解析css文件,所以会出现报错|使用**asset-require-hook**插件排除css,也可以排除sass文件,防止nodejs读取css报错.
```
**原因**
```
前后端生成的css-modules不同,造成了部署到服务器时,会造成读不到样式,然后页面闪现问题|原因是由于使用的组件**css-modules-require-hook**也是根据css-modules的机制,以file-path路径进行生成的hash,所以由于css-modules-require-hook和webpack的目录不同,所以造成了生成的hash不一样只的问题|只需要在css-modules-require-hook组件中使用rootDir,将两个目录一致即可
```
**解决方案**
```
后端React 使用renderToString渲染 图片路径变为hash码名称|原因是由于Nodejs加载文件时,会自动转为hash名称|使用插件asset-require-hook钩子来返回正确的图片名称
```
```js
require('asset-require-hook')({
extensions: [
'jpg', 'png', 'gif', 'webp'
],
name: '[name].[ext]',
limit: 2000
});
```
<h2 align="center">后端权限验证类</h2>
**问题**
```
使用passport时,一直无法写入cookie,并无法验证通过
```
**原因**
```
原因是由于没有在执行代码的时候,写入await让验证操作执行完在进行后续操作,造成了问题
```
**解决方案**
```
只需要增加await,等待异步执行完成后传接成功内容给http body,代码如下:
```
```js
await passport.authenticate('local', function(err, user, info, status) {.....}
```
<h2 align="center">协议</h2>
MIT
17 changes: 6 additions & 11 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ require('asset-require-hook')({
name: '/dist/img/[name].[ext]',
limit: 2000
});
//load common config
const common = require('./common.json');

let path = require('path');

//Css modules hook
require('css-modules-require-hook')({
generateScopedName: '[name]_[local]_[hash:base64:3]',
camelCase: true,
rootDir:'./client/'
});
require('css-modules-require-hook')({generateScopedName: '[name]_[local]_[hash:base64:3]', camelCase: true, rootDir: './client/'});

let
//加载koa主模块
Expand All @@ -37,9 +35,6 @@ let
session = require('koa-session'),
routers = require('./server/route/router.js');




//初始化koa对象
const App = () => {
//创建koa服务器应用
Expand Down Expand Up @@ -82,14 +77,14 @@ const App = () => {
return app;
};

//Creat koa server and listen at 8000
//Creat koa server and listen
var creatServer = () => {
const app = App();
app.listen(3000, function(err) {
app.listen(common.serverPort, function(err) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
console.log('Listening at localhost:' + common.serverPort);
});
};

Expand Down
2 changes: 1 addition & 1 deletion client/.babelrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"presets": ["react", ["es2015", {"modules": false}], "stage-0", "stage-1", "stage-2", "stage-3"],
"presets": ["react", "es2015", "stage-0", "stage-1", "stage-2", "stage-3"],
"plugins": ["react-hot-loader/babel","transform-runtime"]
}
8 changes: 5 additions & 3 deletions client/config/devServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
//加载webpack配置文件
const config = require('./webpack.config.dev');
//载入默认配置
const common = require('../../common.json');

//配置及初始化Koa服务器
var creatServer = () => {
Expand All @@ -20,12 +22,12 @@ var creatServer = () => {
colors: true // 用颜色标识
}
});
//调用开启5000端口用来测试和开发
app.listen(5000, function(err) {
//调用开启端口用来测试和开发
app.listen(common.clientPort , function(err) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:5000');
console.log('Listening at localhost:'+common.clientPort);
});
};

Expand Down
25 changes: 23 additions & 2 deletions client/src/data/mock.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
import Mock from 'mockjs';

Mock.mock('http://localhost:5000/login', {
Mock.mock('/login', {
'success': true,
'status': 200,
'message': '登录成功',
'message': '登录失败!',
'data': {}
});

Mock.mock('/vaildate_user', {
'success': true,
'status': 200,
'message': '用户名有重复!',
'data': {}
});

Mock.mock('/vaildate_email', {
'success': true,
'status': 200,
'message': '邮箱已被占用!',
'data': {}
});

Mock.mock('/reg_user', {
'success': true,
'status': 200,
'message': '注册失败!',
'data': {}
});
3 changes: 3 additions & 0 deletions client/src/redux/actions/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import * as types from '../constants/ActionTypes'

export const increment = () => ({ type: types.INCREMENT })
//user
export const login = () => ({ type: types.LOGIN })
export const logout = () => ({ type: types.LOGOUT })
2 changes: 2 additions & 0 deletions client/src/redux/constants/ActionTypes.js
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const INCREMENT = 'INCREMENT'
export const LOGIN = 'LOGIN' //user logined
export const LOGOUT = 'LOGOUT' //user logout
2 changes: 1 addition & 1 deletion client/src/redux/store/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import configureStore from './configureStore'

const store = configureStore()
const store = configureStore(window.__REDUX_DATA__)

export default store
13 changes: 8 additions & 5 deletions client/src/redux/store/middlewares.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { applyMiddleware } from 'redux';
import {applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

export default applyMiddleware(
thunk , logger
)
let middleWare;
if (process.env.NODE_ENV === 'production') {
middleWare = applyMiddleware(thunk);
} else {
middleWare = applyMiddleware(thunk, logger);
}
export default middleWare;
19 changes: 8 additions & 11 deletions client/src/view/components/login_form.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,26 @@
import React, {Component} from 'react';
import ReactDOM, {render} from 'react-dom';
import {Field, reduxForm, SubmissionError} from 'redux-form';
import {browserHistory} from 'react-router';
import {connect} from 'react-redux';
import axios from 'axios';
// import Mock from 'mockjs';
import * as actions from '../../redux/actions/index';

import Login from '../../dist/css/login.css';

// Mock.mock('/login', {
// 'success': true,
// 'status': 200,
// 'message': '登录失败!',
// 'data': {}
// });
if (process.env.NODE_ENV !== 'production') {
require('../../data/mock');
}

const submit = async function submit(values) {
let _this = this;
console.log(_this);
await axios.post('/login', values).then(function(response) {
console.log(response);
if (!response.data.success) {
throw new SubmissionError({_error: response.data.message});
} else {
_this.props.dispatch({type: 'LOGIN'});
browserHistory.push('/');
_this.props.login();
_this.props.history.push('/');
}
})
}
Expand Down Expand Up @@ -68,4 +65,4 @@ class LoginForm extends Component {
}
};

export default connect()(reduxForm({form: 'login_form'})(LoginForm));
export default connect(null, actions)(reduxForm({form: 'login_form'})(LoginForm));
Loading

0 comments on commit 9ade40b

Please sign in to comment.