React·续1

// src/constants/index.tsxexport const INCREMENT_ENTHUSIASM = 'INCREMENT_ENTHUSIASM';export type INCREMENT_ENTHUSIASM = typeof INCREMENT_ENTHUSIASM;export const DECREMENT_ENTHUSIASM = 'DECREMENT_ENTHUSIASM';export type DECREMENT_ENTHUSIASM = typeof DECREMENT_ENTHUSIASM;

这里的const/type模式允许我们以容易访问和重构的方式使用TypeScript的字符串字面量类型。

接下来,我们创建一些actions以及创建这些actions的函数,src/actions/index.tsx。

import * as constants from '../constants'export interface IncrementEnthusiasm {    type: constants.INCREMENT_ENTHUSIASM;}export interface DecrementEnthusiasm {    type: constants.DECREMENT_ENTHUSIASM;}export type EnthusiasmAction = IncrementEnthusiasm | DecrementEnthusiasm;export function incrementEnthusiasm(): IncrementEnthusiasm {    return {        type: constants.INCREMENT_ENTHUSIASM    }}export function decrementEnthusiasm(): DecrementEnthusiasm {    return {        type: constants.DECREMENT_ENTHUSIASM    }}

我们创建了两个类型,它们负责增加操作和减少操作的行为。 我们还定义了一个类型(EnthusiasmAction),它描述了哪些action是可以增加或减少的。 最后,我们定义了两个函数用来创建实际的actions。

这里有一些清晰的模版,你可以参考类似redux-actions的库。

添加reducer

现在我们可以开始写第一个reducer了! Reducers是函数,它们负责生成应用state的拷贝使之产生变化,但它并没有副作用。 它们是一种纯函数。

我们的reducer将放在src/reducers/index.tsx文件里。 它的功能是保证增加操作会让感叹级别加1,减少操作则要将感叹级别减1,但是这个级别永远不能小于1。

// src/reducers/index.tsximport { EnthusiasmAction } from '../actions';import { StoreState } from '../types/index';import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';export function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {  switch (action.type) {    case INCREMENT_ENTHUSIASM:      return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };    case DECREMENT_ENTHUSIASM:      return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };  }  return state;}

注意我们使用了对象展开(...state),当替换enthusiasmLevel时,它可以对状态进行浅拷贝。 将enthusiasmLevel属性放在末尾是十分关键的,否则它将被旧的状态覆盖。

你可能想要对reducer写一些测试。 因为reducers是纯函数,它们可以传入任意的数据。 针对每个输入,可以测试reducers生成的新的状态。 可以考虑使用Jest的toEqual方法。

创建容器

在使用Redux时,我们常常要创建组件和容器。 组件是数据无关的,且工作在表现层。 容器通常包裹组件及其使用的数据,用以显示和修改状态。 你可以在这里阅读更多关于这个概念的细节:Dan Abramov写的表现层的容器组件。

现在我们修改src/components/Hello.tsx,让它可以修改状态。 我们将添加两个可选的回调属性到Props,它们分别是onIncrement和onDecrement:

export interface Props {  name: string;  enthusiasmLevel?: number;  onIncrement?: () => void;  onDecrement?: () => void;}

然后将这两个回调绑定到两个新按钮上,将按钮添加到我们的组件里。

function Hello({ name, enthusiasmLevel = 1, onIncrement, onDecrement }: Props) {  if (enthusiasmLevel <= 0) {    throw new Error('You could be a little more enthusiastic. :D');  }  return (    <​div className="hello">      <​div className="greeting">        Hello {name + getExclamationMarks(enthusiasmLevel)}      <​/div>      <​div>        <​button onClick={onDecrement}>-<​/button>        <​button onClick={onIncrement}>+<​/button>      <​/div>    <​/div>  );}

通常情况下,我们应该给onIncrement和onDecrement写一些测试,它们是在各自的按钮被点击时调用。 试一试以便掌握编写测试的窍门。

现在我们的组件更新好了,可以把它放在一个容器里了。 让我们来创建一个文件src/containers/Hello.tsx,在开始的地方使用下列导入语句。

import Hello from '../components/Hello';import * as actions from '../actions/';import { StoreState } from '../types/index';import { connect, Dispatch } from 'react-redux';

两个关键点是初始的Hello组件和react-redux的connect函数。 connect可以将我们的Hello组件转换成一个容器,通过以下两个函数:

  • mapStateToProps将当前store里的数据以我们的组件需要的形式传递到组件。

  • mapDispatchToProps利用dispatch函数,创建回调props将actions送到store。

回想一下,我们的应用包含两个属性:languageName和enthusiasmLevel。 我们的Hello组件,希望得到一个name和一个enthusiasmLevel。 mapStateToProps会从store得到相应的数据,如果需要的话将针对组件的props调整它。 下面让我们继续往下写。

export function mapStateToProps({ enthusiasmLevel, languageName }: StoreState) {  return {    enthusiasmLevel,    name: languageName,  }}

注意mapStateToProps仅创建了Hello组件需要的四个属性中的两个。 我们还想要传入onIncrement和onDecrement回调函数。 mapDispatchToProps是一个函数,它需要传入一个调度函数。 这个调度函数可以将actions传入store来触发更新,因此我们可以创建一对回调函数,它们会在需要的时候调用调度函数。

export function mapDispatchToProps(dispatch: Dispatch<​actions.EnthusiasmAction>) {  return {    onIncrement: () => dispatch(actions.incrementEnthusiasm()),    onDecrement: () => dispatch(actions.decrementEnthusiasm()),  }}

最后,我们可以调用connect了。 connect首先会接收mapStateToProps和mapDispatchToProps,然后返回另一个函数,我们用它来包裹我们的组件。 最终的容器是通过下面的代码定义的:

export default connect(mapStateToProps, mapDispatchToProps)(Hello);

现在,我们的文件应该是下面这个样子:

// src/containers/Hello.tsximport Hello from '../components/Hello';import * as actions from '../actions/';import { StoreState } from '../types/index';import { connect, Dispatch } from 'react-redux';export function mapStateToProps({ enthusiasmLevel, languageName }: StoreState) {  return {    enthusiasmLevel,    name: languageName,  }}export function mapDispatchToProps(dispatch: Dispatch<​actions.EnthusiasmAction>) {  return {    onIncrement: () => dispatch(actions.incrementEnthusiasm()),    onDecrement: () => dispatch(actions.decrementEnthusiasm()),  }}export default connect(mapStateToProps, mapDispatchToProps)(Hello);

创建store

让我们回到src/index.tsx。 要把所有的东西合到一起,我们需要创建一个带初始状态的store,并用我们所有的reducers来设置它。

import { createStore } from 'redux';import { enthusiasm } from './reducers/index';import { StoreState } from './types/index';const store = createStore<​StoreState>(enthusiasm, {  enthusiasmLevel: 1,  languageName: 'TypeScript',});

store可能正如你想的那样,它是我们应用全局状态的核心store。

接下来,我们将要用./src/containers/Hello来包裹./src/components/Hello,然后使用react-redux的Provider将props与容器连通起来。 我们将导入它们:

import Hello from './containers/Hello';import { Provider } from 'react-redux';

将store以Provider的属性形式传入:

ReactDOM.render(  <​Provider store={store}>    <​Hello />  <​/Provider>,  document.getElementById('root') as HTMLElement);

注意,Hello不再需要props了,因为我们使用了connect函数为包裹起来的Hello组件的props适配了应用的状态。

退出

如果你发现create-react-app使一些自定义设置变得困难,那么你就可以选择不使用它,使用你需要配置。 比如,你要添加一个Webpack插件,你就可以利用create-react-app提供的“eject”功能。

运行:

npm run eject

这样就可以了!

你要注意,在运行eject前最好保存你的代码。 你不能撤销eject命令,因此退出操作是永久性的除非你从一个运行eject前的提交来恢复工程。

下一步

create-react-app带有很多很棒的功能。 它们的大多数都在我们工程生成的README.md里面有记录,所以可以简单阅读一下。

如果你想学习更多关于Redux的知识,你可以前往官方站点查看文档。 同样的,MobX官方站点。

如果你想要在某个时间点eject,你需要了解再多关于Webpack的知识。 你可以查看React & Webpack教程。

有时候你需要路由功能。 已经有一些解决方案了,但是对于Redux工程来讲react-router是最流行的,并经常与react-router-redux联合使用。