使用redux第一步
npm install --save react-redux
用Provider包裹住app;
且建立store,将reducer中的函数放入createstore;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import {createStore} from 'redux';
import reducer from './store/reducer';
import {Provider} from 'react-redux'; //用于将store放入react
//create store
const store = createStore(reducer);
//传入store到app
ReactDOM.render(
<Provider store={store}>
<App />
</Provider> , document.getElementById('root'));
registerServiceWorker();
Updating state immutably
在reducer中改变state,需要使用immutably方法
const initialState = {
counter:0,
results:[]
}
const reducer = (state=initialState, action) =>{
switch (action.type){
case 'INCREMENT':
//object.assign 对object类型进行copy,但state中的array并不会进行深拷贝
//const newState = Object.assign({},state);
return { //return一个obj,不在原地修改
...state,
counter:state.counter+1
};
case 'DECREMENT':
return{
...state,
counter:state.counter-1
};
case 'ADD':
return {
...state,
counter:state.counter+action.val
};
case 'SUB':
return {
...state,
counter:state.counter-action.val
};
case 'STORE_RESULT':
return{
...state,
results:state.results.concat({id:new Date(),value:state.counter}) //concat返回一个新的array,并添加元素
};
}
return state; //需要默认传回原始数据——防止错误dispatch导致数据丢失
}
export default reducer;
每次返回一个新的obj,可以使用state的内容,但不能改变state的内容;
用concat代替push,因为concat返回新的array;
将多个state参数传入ui
用map将传入的array显示为li;
import React, { Component } from 'react';
import CounterControl from '../../components/CounterControl/CounterControl';
import CounterOutput from '../../components/CounterOutput/CounterOutput';
import {connect} from 'react-redux';
class Counter extends Component {
render () {
return (
<div>
<CounterOutput value={this.props.ctr} />
<CounterControl label="Increment" clicked={this.props.onIncrementCounter} />
<CounterControl label="Decrement" clicked={this.props.onDecrementCounter} />
<CounterControl label="Add 5" clicked={this.props.onAdd} />
<CounterControl label="Subtract 5" clicked={this.props.onSub} />
<hr/>
<button onClick={this.props.onStoreResult}>Store Result</button>
<ul>
{this.props.storeResults.map(strResult=>{
return(
<li key={strResult.id} onClick={this.props.onDeleteResult}>{strResult.value}</li>
)
})}
</ul>
</div>
);
}
}
//在class后定义,将reducer中的state选部分作为props传入上面的component中
const mapStateToProps = state=>{ //从reducer中引入state.counter,作为ctr在此使用
return {
ctr:state.counter,
storeResults: state.results
};
}
//传入需要dispatch的action
const mapDispatchToProps = dispatch=>{
return {
onIncrementCounter: ()=> dispatch({type:'INCREMENT'}),
//设置Decrement
onDecrementCounter: ()=> dispatch({type:'DECREMENT'}),
//设置Add
onAdd:()=>dispatch({type:'ADD',val:5}),
onSub:()=>dispatch({type:"SUB",val:5}),
onStoreResult:()=> dispatch({type:'STORE_RESULT'}) //无需传入,已有val传入
,onDeleteResult:()=> dispatch({type:'DELETE_RESULT'})
};
}
//传入需要的stateprops和dispatch props
export default connect(mapStateToProps,mapDispatchToProps)(Counter);
//connect() 返回一个hoc funtion
将state中的array内容部分删除
方法1:
不能直接用splice,要对copy用splice;
case 'DELETE_RESULT':
const id =2;
// state.results.splice(id,1); //会改变原本的array
//方法1:copy
const newArray = [...state.results]; //若array中有obj,则obj还是指向原本的地址
newArray.splice(id,1); //remove 无所谓,不改变其中的obj内容就行
return {
...state,
results:newArray
}
方法2:filter
array.filter()返回一个新array,其中function返回true,说明该元素被添加,返回false则该元素被忽略;
case 'DELETE_RESULT':
const updatedArray = state.results.filter((result)=> result.id !== action.resultElId);
//返回一个新array,对每个el进行funtion,返回true则加入新array,false则忽略不加入新array
return {
...state,
results:updatedArray
}
需要往reducer中传入一个id;
往reducer中传入id
设置函数时代入id参数;
onDeleteResult:(id)=> dispatch({type:'DELETE_RESULT',resultElId:id})
设置onclick时调用函数时传入id参数;
{this.props.storeResults.map(strResult=>{
return(
<li key={strResult.id} onClick={()=>this.props.onDeleteResult(strResult.id)}>{strResult.value}</li>
)
})}
优化——将actiontype存放在一个js文件中,防止打错
现在在reducer中设置actiontype的event;
在container中调用dispatch(action.type);
若是两者打错则难以找到错误;
构建actions.js
将所有的type都放入其中;
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const ADD = 'ADD';
export const SUB = 'SUB';
export const STORE_RESULT = 'STORE_RESULT';
export const DELETE_RESULT = 'DELETE_RESULT';
在reducer中调用action.js
import * as actionTypes from './action';
在container中调用action.js
import * as actionType from '../../store/action';
将所有用到type的地方都出啊如actionType.type即可;
//传入需要dispatch的action
const mapDispatchToProps = dispatch=>{
return {
onIncrementCounter: ()=> dispatch({type:actionType.INCREMENT}),
//设置Decrement
onDecrementCounter: ()=> dispatch({type:actionType.DECREMENT}),
//设置Add
onAdd:()=>dispatch({type:actionType.ADD,val:5}),
onSub:()=>dispatch({type:actionType.SUB,val:5}),
onStoreResult:()=> dispatch({type:actionType.STORE_RESULT}) //无需传入,已有val传入
,onDeleteResult:(id)=> dispatch({type:actionType.DELETE_RESULT,resultElId:id})
};
}
优化——将reducer分为不同的js,再合并
reducer-result
state中含有results数组;
import * as actionTypes from '../action';
const initialState = {
results:[]
}
const reducer = (state=initialState, action) =>{
switch (action.type){
case actionTypes.STORE_RESULT:
return{
...state, //可以调用counter,因为两reducer最后会合并
results:state.results.concat({id:new Date(),value:action.result}) //concat返回一个新的array,并添加元素
};
case actionTypes.DELETE_RESULT:
const updatedArray = state.results.filter((result)=> result.id !== action.resultElId);
return {
...state,
results:updatedArray
}
}
return state; //需要默认传回原始数据——防止错误dispatch导致数据丢失
}
export default reducer;
reducer-counter
state中含有counter计数器;
import * as actionTypes from '../action';
const initialState = {
counter:0
};
const reducer = (state=initialState, action) =>{
switch (action.type){
case actionTypes.INCREMENT:
//object.assign 对object类型进行copy,但state中的array并不会进行深拷贝
//const newState = Object.assign({},state);
return { //return一个obj,不在原地修改
...state,
counter:state.counter+1
};
case actionTypes.DECREMENT:
return{
...state,
counter:state.counter-1
};
case actionTypes.ADD:
return {
...state,
counter:state.counter+action.val
};
case actionTypes.SUB:
return {
...state,
counter:state.counter-action.val
};
}
return state; //需要默认传回原始数据——防止错误dispatch导致数据丢失
}
export default reducer;
再index.js即创建store的地方将reducer合并;
combineReducers()传入一个obj,为key:reducer;
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import {createStore, combineReducers} from 'redux';
import counterReducer from './store/reducers/counter';
import resultReducer from './store/reducers/result';
import {Provider} from 'react-redux'; //用于将store放入react
const rootreducer = combineReducers({ //将多个reducer合并为一个
ctr: counterReducer,
res: resultReducer
});
//create store
const store = createStore(rootreducer);
//传入store到app
ReactDOM.render(
<Provider store={store}>
<App />
</Provider> , document.getElementById('root'));
registerServiceWorker();
在container中调用合并后的reducer
在container中传入store的state:
需要使用combinereducer()时使用的key来调用;
//在class后定义,将reducer中的state选部分作为props传入上面的component中
const mapStateToProps = state=>{ //从reducer中引入state.counter,作为ctr在此使用
return {
ctr:state.ctr.counter,
storeResults: state.res.results
};
}
在两个分开的reducer中互相调用state参数;
在dispatch时将要用到的参数传入该reduce中;
onStoreResult:(result)=> dispatch({type:actionType.STORE_RESULT,result:result})
在设置onclick等事件时调用该函数——传入对应的参数;
<button onClick={()=>this.props.onStoreResult(this.props.ctr)}>Store Result</button>
在reducer中调用——作为action参数调用;
results:state.results.concat({id:new Date(),value:action.result})
本文介绍了使用Redux进行状态管理的基本步骤和优化技巧,包括不可变地更新state、将多个state参数传递给UI、从state中删除数组元素、通过id操作state、将action type集中管理、将reducer拆分和合并,以及在不同reducer间共享state参数。
43

被折叠的 条评论
为什么被折叠?



