以计数器为例
使用命令搭好项目之后,安装 redux,react-redux 即可。
index.js 页面中创建 store
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import { reducer } from './reducer'
const store = createStore(reducer)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
reducer.jsx
import { INCREMENT, DECREMENT } from '../constants'
export const reducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
default:
return state
}
}
constants.jsx
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
创建 action.jsx
import { DECREMENT, INCREMENT } from '../constants'
export const increment = () => ({
type: INCREMENT
})
export const decrement = () => ({
type: DECREMENT
})
无状态组件 Counter.jsx
import React from 'react'
export default class Counter extends React.PureComponent {
render() {
const { value, onIncrement, onDecrement } = this.props;
return (
<p>
Clicked: {value} times
<br />
<button onClick={onIncrement} style={{ marginRight: 20 }}> + </button>
<button onClick={onDecrement}> - </button>
</p>
)
}
}
容器组件 CountCon.jsx
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import { decrement, increment } from '../actions'
const mapStateToProps = (state) => ({
value: state
})
const mapDispatchToProps = (dispatch) => ({
onDecrement: () => dispatch(decrement()),
onIncrement: () => dispatch(increment())
})
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
现在我们的页面可以正常运行了。
为什么会出现 TypeScript?
TypeScript的设计目的应该是解决JavaScript的“痛点”:弱类型和没有命名空间,导致很难模块化,不适合开发大型程序。
对应于项目来说,有数据输出输入的地方,就可以使用 TypeScript。
以上面写好的计时器来说
备注:对于项目如何支持 TypeScript,请各位自行百度
reducer 就是一个典型存在输入输出。
export const reducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1
case DECREMENT:
return state - 1
default:
return state
}
}
action
export type ModifyAction = IINCREMENTAction | IDECREMENTAction;
export interface IINCREMENTAction {
type: INCREMENT;
}
export interface IDECREMENTAction {
type: DECREMENT;
}
reducer 返回的是数字,我们也应当显示的声明
export default (state = 0, action: ModifyAction): number => {}
对于无状态组件,接收来自外界的值,也应当使用接口进行显示声明
// 创建类型接口
export interface IProps {
value: number;
onIncrement: () => void;
onDecrement: () => void;
}
export default class Counter extends React.PureComponent<IProps> {}
容器组件中的 mapStateToProps
与 mapDispatchToProps
也是典型的输入输出。
// 将 reducer 中的状态插入到组件的 props 中
const mapStateToProps = (state: number): { value: number } => ({
value: state
})
// 将 对应action 插入到组件的 props 中
const mapDispatchToProps = (dispatch: Dispatch) => ({
onDecrement: () => dispatch(decrement()),
onIncrement: () => dispatch(increment())
})