React 笔记

# react-redux

注:react-native + react-redux 的配置说明请看我另一篇文章。 和 web 版略有不同。

# 一个简单的例子

import React from "react";
import ReactDOM from "react-dom";
import { createStore, combineReducers } from "redux";
import { Provider, connect } from "react-redux";

const reducer = (state = {}, action) => {
  switch (action.type) {
    case "test":
      return { ...state, ...{ demo: action.data } };
    default:
      return state;
  }
};

const store = createStore(reducer);

// 不稳定的语法,ES7 装饰器
// @connect(mapStateToProps,mapDispatchToProps)
class App extends React.Component {
  render() {
    return (
      <div>
        <div onClick={ev => this.props.triggerFun("WOW!")}>Hello</div>
        <div>{this.props.demo}</div>
      </div>
    );
  }
}

const mapStateToProps = state => ({ demo: state.demo });
const mapDispatchToProps = dispatch => ({
  triggerFun: data => dispatch({ type: "test", data: data }),
});
const AppView = connect(
  mapStateToProps,
  mapDispatchToProps,
)(App);

ReactDOM.render(
  <Provider store={store}>
    <AppView />
  </Provider>,
  document.getElementById("react-root"),
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

如果使用了路由:

class MainPage extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <Router>
          <div>
            <Route exact path="/" component={HelloView} />
          </div>
        </Router>
      </Provider>
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 补充

一般情况下,业务逻辑不会写在 reducer 中,我们封装一个 action 层来处理业务逻辑。

// 使用 actions 进行逻辑包装

const actions = {
  addCharts: (x, y, name, type) => {
    return (dispatch, getState) => {
      const state = getState();
      const charts = [...state.charts];
      charts.push({ x, y, name, type });
      dispatch({ type: "SET_CHARTS", charts });
    };
  },
  deleteChartView: index => {
    return (dispatch, getState) => {
      const state = getState();
      const charts = [...state.charts];
      charts.splice(index, 1);
      dispatch({ type: "SET_CHARTS", charts });
    };
  },
  changeChartViewPos: (index, x, y) => {
    return (dispatch, getState) => {
      const state = getState();
      const charts = [...state.charts];
      charts[index].x = x;
      charts[index].y = y;
      dispatch({ type: "SET_CHARTS", charts });
    };
  },
};

export default actions;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

我们看到,上面的代码返回了一个函数,与我们标准的 action 生成函数有区别,这是因为这里使用了 redux-thunk。

redux-thunk 是一个中间件,提供 action 处理异步的能力,使用方式很简单:

// 和浏览器调试中间件联用的方式
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk)));
1
2
3
4
5
6

然后我们就能使用 action 生成函数了。

import { connect } from "react-redux";
import actions from "../store/actions.js";
// ...
const mapStateToProps = state => ({});
const mapDispatchToProps = dispatch => ({
  deleteChartView: index => dispatch(actions.deleteChartView(index)),
  changeChartViewPos: (index, x, y) =>
    dispatch(actions.changeChartViewPos(index, x, y))
});
1
2
3
4
5
6
7
8
9

# React 中类型校验(新旧写法差异)

# 新版

// After (15.5)
import React from "react";
import PropTypes from "prop-types";
class Component extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}
Component.propTypes = {
  text: PropTypes.string.isRequired,
};
1
2
3
4
5
6
7
8
9
10
11

# 旧版

// Before (15.4 and below)
import React from "react";
class Component extends React.Component {
  render() {
    return <div>{this.props.text}</div>;
  }
}
Component.propTypes = {
  text: React.PropTypes.string.isRequired,
};
1
2
3
4
5
6
7
8
9
10