redux

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值