• 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 }
    }
    
  • 相关阅读:
    java上传视频文件
    java+HTML5实现断点续传
    web+上传大文件断点续传
    javaweb项目断点续传
    CKEditor从word粘贴问题
    netback的tasklet调度问题及网卡丢包的简单分析
    linux下开启ftp的21号port
    Dubbo--简单介绍
    OpenCV2马拉松第15圈——边缘检測(Laplace算子,LOG算子)
    【打CF,学算法——一星级】Codeforces Round #313 (Div. 2) A. Currency System in Geraldion
  • 原文地址:https://www.cnblogs.com/cyany/p/12798224.html
Copyright © 2020-2023  润新知