redux = reducer+flux;
数据层框架
flux 有缺陷
升级成了redux
redux特点
- store必须是唯一的
- 只有store能够改变自己的内容,reducer修改的只是state中的副本,改变副本并返回数据,而真正修改数据的是store本身
- reducer必须是纯函数,不能使用new Date(),不能请求接口,不能有副作用,不能修改参数(纯函数:固定的输入,会有固定的输出)
使用redux步骤
import {createStore} from 'redux';
import reducer from './reducer';
const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ &&window.__REDUX_DEVTOOLS_EXTENSION__() // chrome调试redux
); // 把笔记本reducer传递给store
export default store;
reducer
const defaultState={
inputValue:'123',
list:['3333','fff'],
}
// reducer可以接收state,但是不能修改state--时间回溯
export default (state=defaultState,action)=>{
// 笔记本 操作数据的本 state,store里面存储的数据
// state是旧的prevState
if(action.type =='change_input_value'){
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
if(action.type =='add_todo_item'){
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
return newState;
}
return state;
}
初始化的store有了初始化的state和reducer,组件内如何使用?
import store from './store'; // redux-store
this.state = store.getState();
componentDidMount(){
store.subscribe(this.handleStoreChange)
// 本组件订阅store,store数据修改,subScribe里的回调函数会自动执行
}
定义action并触发action
handleInputChange=(e)=>{
// 告诉store,把store中的inputValue修改掉
const action={
type:'change_input_value', // 告诉redux,要做的事情
value:e.target.value,
}
store.dispatch(action) // 把话传给store->store会自动转给reducer
}