和 vue 一样,react 也有脚手架: create-react-app
我们将在这上面进行开发
脚手架安装:
- npm install -g create-react-app
- create-react-app my-app
- cd my-app
生成的目录结构:
如上我们主要动 index.js 和 App.js
运行程序:
npm start
接下来我们在 App.js 写下:
- //App.js
- import React, {Component} from 'react';
- //【3】.根据传来的不同action标识判断应该做出的反应。
- //如action的type为INCREMENT时,那么做出的反应就是计算某值,
- //并将该值返回做为一个新的state
- //reducer
- const counter = (state = { value: 0 }, action) => {
- switch (action.type) {
- case 'INCREMENT':
- return { value: state.value + 1 };
- case 'DECREMENT':
- return { value: state.value - 1 };
- default:
- return state;
- }
- }
- class MyCounter01 extends Component {
- // State 初始化数据state状态
- constructor() {
- super();
- this.state = counter(undefined,{});
- }
- //【2】.dispatch调用counter函数【即reducer】,
- //参数:数据当前的状态state和action动作(该action动作以type字段为标识)
- dispatch(action) {
- //【4】.以reducer返回的新state更新状态,通过this.setState方法修改状态值
- this.setState(prevState => counter(prevState, action));
- }
- // Actions
- increment = () => {
- this.dispatch({ type: 'INCREMENT' });
- };
- decrement = () => {
- this.dispatch({ type: 'DECREMENT' });
- };
- //view层
- render() {
- return (
- <p>
- <p>{this.state.value}</p>
- //【1】. 用户点击加按钮,触发this.increment函数【即action】
- //函数通过 this.dispatch发出action,告诉数据你应该要发生变化啦
- <button onClick={this.increment}>+</button>
- <button onClick={this.decrement}>-</button>
- </p>
- )
- }
- }
- export default MyCounter01;
代码中标的 1234 点就是以下工作流的具体实施过程。
本节中只需要理解
和以往的点击函数实现加减不同,react 明显多了两个跳板,一步一步渐进的完成整个动作。
action 状态:根据用户的操作事件分发(dispatch)动作(action),每个动作由 type 标识
reducer:将收到的状态分流,规定某个状态对应数据的怎么变化,并返回一个新数据 state
具体根据数据变化更新数据的:this.setState()
来源: https://www.2cto.com/kf/201712/709405.html