小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
介绍
Redux是一个用来管理管理数据状态和UI状态的JavaScript应用工具。随着JavaScript单页应用(SPA)开发日趋复杂,JavaScript需要管理比任何时候都要多的state(状态),需要Redux来降低管理的难度
Redux与Vuex 类似都属于管理状态的工具,并不是每一个项目都必须使用他们,你也可以选择不使用他
Redux流程图
Redux步骤
1.创建store
npm install --save redux //安装redux
在src下创建store文件下,在其下创建index.js文件,新建reducer.js
// ./store/index.js
import { createStore } from 'redux' // 引入createStore方法
import reducer from './reducer'
const store = createStore(reducer) // 创建数据存储仓库
export default store //暴露出去
// reducer.js
const defaultState = {} //默认数据
export default (state = defaultState,action)=>{ //就是一个方法函数
return state
}
2.使用store.getState()获取初始化状态
// App.js
import React, { Component } from "react";
import store from './store' //引入store
class App extends Component {
constructor(props) {
this.state = store.getState();
}
}
3.创建action、dispatch传递action
想要改变redux中state的值,只能通过Action了。action就创建好了,需要通过dispatch()方法传递给store
changeValue(e){
const action ={
type:'changevalue',
value:'e.target.value'
}
store.dispatch(action)
}
4.store与reducer 的数据传递
store只是一个仓库,并没有管理能力,会把接受到的action转发给reducer
reducer不能直接修改state需要声明一个newState return返回给store重新createStore
export default (state = defaultState,action)=>{
if(action.type === 'changeInput'){
let newState = JSON.parse(JSON.stringify(state)); //需要使用深拷贝
newState.inputValue = action.value;
return newState;
return state //返回给store
}
}
5.store数据更新,编写代码使组件更新
constructor(props){
this.state = store.getState()
store.subscribe(this.storeChange) //订阅Redux的状态 发生改变触发
}
this.storeChange=()=>{ //注意使用箭头函数 this转向
this.setState(store.getState())
}
以上就是Redux的基础步骤,后续文章请查看(二)