React开发实践之(4)redux入门

168 阅读2分钟

1、入门概念

  • react是 视图层框架

  • redux是 数据层

  • 基本思想 将数据保存在 store 中,当一个组件的数据发生变化时,其他来取这个组件的数据也就发生了变化, 其实做了两件事情

    1、数据都放在一个 store 中管理 不同组件引用 store 的数据
    2、一个组件数据变化 则会引起 其他组件数据的变化 
    

image.png

image.png

2、redux 工作流程

image.png

  • 画一遍

3、使用 antd 编写 todoList

    1、安装  yarn add antd
    2、引入  
    3、需要特别注意引入 样式文件 import 'antd/dist/antd.css';
    4、使用 
    
    

image.png

  • 代码放在地下
import { Input, Button, List } from "antd";
import "antd/dist/antd.css";

class TodoList extends Component {
  render() {
    const data = ["test", "test2", "test3"];
    return (
      <>
        <div>
          <Input
            placeholder="TodoList"
            style={{
              width: "300px",
              marginRight: "10px",
              marginLeft: "10px",
              marginTop: "10px",
            }}
          />
          <Button type="primary">提交</Button>
        </div>
        <List
          style={{ width: "300px", marginLeft: "10px" }}
          dataSource={data}
          renderItem={(item) => <List.Item>{item}</List.Item>}
        />
      </>
    );
  }
}

export default TodoList;

  • 当然 工作中 一般不会直接将 css 写在 此处,会单独使用 css 文件写

4、 store 的创建

image.png

image.png

  • 组件内使用 数据

image.png

  • 我们只需 将这个拿到的数据给 state 就可使用了

image.png

  • 非常 开心的是可以看到数据 !

image.png

5、 action creator

  • 先安装 redux 调试工具

    1、安装 
    2、配置一下  创建store时 第二个参数传递 这个东西 
    

image.png

image.png

  • 将数据更新 整个流程走一遍 ?

  • 此处 组件数据 --> action --> store

image.png

image.png

  • 非常 开心的事情, 当 触发 dispatch(action) 时 store 会自动将 (prevState,action) 推给 Reducers

image.png

  • 此时Reducers 处理 数据 并且返回 newState

image.png

  • 但是页面数据还未更新,因为页面数据依赖的是 state 更改

image.png

image.png

  • 更改页面 state 就可更新页面

image.png

image.png

  • 非常开心的一件事情!

* 梅开二度, 我们再尝试更新 list 的内容

  • 点击按钮后将内容 放到下面

image.png

  • store 不知道怎么处理,会将 之前的 state和当前的 action 传递给 Reducers处理 并且 返回一个新的 state (prevState,action)

image.png

  • 因为组件内 有监听 store 变化 并且更新了 state 所以 组件重新渲染

image.png

  • 将 input 内容 提交到 list 中 非常nice的 实现了 !

image.png

6、 完成删除功能

image.png

image.png

image.png

  • 页面效果 可以实现 点击删除 非常nice!

image.png

7、 action Type 拆分

  • 拆分的目的是 为了在出现问题时,快速定位到问题

image.png

image.png

image.png

8、 使用 action Creator 统一创建 action (重要)

image.png

image.png

image.png

  • 非常nice ~

9、 小结 + 补充

  • 重要的小结

      1、store 是唯一的 
      2state 只有 store 能改变 reducer 不能改变 state, 只能拷贝一份 拿到store 给的 (prevState, action) ---> 得到一个新的 newState 给 store 
      3、 Reducer 必须是纯函数,给定 固定的输入,输出则是固定的,不能夹杂 = new Date() 这样的操作,并且不能直接修改 state, 比如 state.value = action.value 
      4、action 是个对象 type 和 payload 
      
    
  • 重要的 API

     1、createStore 创建一个 store 存储数据
     2、store.dispatch(action) 将 action行为 传递到 store 
     3、store.getState() 拿到 store 里的 state
     4、store.subscribe(this.handleXxx) 订阅 store 的变化, store 值更改 则会触发里面的回调函数
    
  • 本节 完 !

撒花 🎉🎉🎉

更多项目请访问 github github.com/huanhunmao

gitee 项目地址 gitee.com/huanhunmao/…