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 }
}
原文地址:https://www.cnblogs.com/cyany/p/12798224.html