zoukankan      html  css  js  c++  java
  • redux初识

    安装

    npm install redux --save
    
    

    使用

    在全局index.js
    
    import { createStore } from 'redux'  //导入createStore()方法
    import reduce from './redux/reduce' //导入reduce,需要作为参数传递到createStore方法里面
    import {addTodo} from './redux/action' //导入需要操作的方法,可以不写这个文件,但是为了便于管理写
    
    
    let store = createStore(reduce);  //创建一个store
    console.log(store,store.getState(),"store");
    store.subscribe(()=> console.log(store.getState()));  //订阅监听,如果store有变动的会执行
    
    store.dispatch(addTodo('Learn about actions'))
    store.dispatch(addTodo('Learn about reducers')) //触发执行方法
    store.dispatch(addTodo('Learn about store'))
    
    
    如果需要给里面的子组件的使用的话,可以用过props传递到给子组件
    
    index.js
       <App store={store} />
    
    child.js
    
    	componentDidMount(){
    		console.log(this.props.store.getState(),"store---useotherstate page");
    		this.props.store.dispatch(addTodo('Learn about js'));
    		this.props.store.subscribe(()=>console.log(this.props.store.getState()))
    	}
    
    

    reduce.js 用来操作的变化过程,但是不能直接改变数据

    import {ADD_TODO,TOGGLE_TODO} from './action';
    const initialState = {
      todos: []
    };
    
    export default function todos(state = [], action) {
      switch (action.type) {
        case ADD_TODO:
          return [
            ...state,
            {
              text: action.text,
              completed: false
            }
          ]
        case TOGGLE_TODO:
          return state.map((todo, index) => {
            if (index === action.index) {
              return Object.assign({}, todo, {
                completed: !todo.completed
              })
            }
            return todo
          })
        default:
          return state
      }
    }
    
    

    action.js

    export const ADD_TODO = 'ADD_TODO';
    /*
     * action 创建函数
     */
    
    export function addTodo(text) {
      return { type: ADD_TODO, text }
    }
    
  • 相关阅读:
    Saltstack module acl 详解
    Saltstack python client
    Saltstack简单使用
    P5488 差分与前缀和 NTT Lucas定理 多项式
    CF613D Kingdom and its Cities 虚树 树形dp 贪心
    7.1 NOI模拟赛 凸包套凸包 floyd 计算几何
    luogu P5633 最小度限制生成树 wqs二分
    7.1 NOI模拟赛 dp floyd
    springboot和springcloud
    springboot集成mybatis
  • 原文地址:https://www.cnblogs.com/cyany/p/12798224.html
Copyright © 2011-2022 走看看