React项目中使用redux

在react项目中使用redux

  1. 安装redux DevTools和在react项目中安装redux(翻墙google应用商店安装)
项目中安装:yarn add redux
或者 npm install redux -S
又或者 cnpm i redux -S
  1. 创建store
import { createStore } from 'redux'; 
import reducer from './reducer';

const store = createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;

在这里插入图片描述

  1. 创建reduer
const defaultState = { // 默认数据
  inputValue: 'focusdroid',
  list: [ '北京', '上海', ]
}
// reducer 只能接受state,决不能修改state
export default (state = defaultState, action) => {
  console.log(state, action)
  if (action.type === 'change_input_value') {
    const newState = JSON.parse(JSON.stringify(state)); // 深拷贝
    newState.inputValue = action.value;
    return newState; // 返回给store
  }
  return state;
}
  1. 在组件中使用store
import store from '../../store/index'

  constructor(props){
    super(props);
    this.state = store.getState()
    this.handleStoreChange = this.handleStoreChange.bind(this)
    store.subscribe(this.handleStoreChange)
  }
   handleStoreChange () { // 让store中的值实时同步
    this.setState(store.getState())
  }

  handleInputChange (e) { // 向store中传递值
    const action = {
      type:'change_input_value',
      value: e.target.value
    }
    store.dispatch(action)
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值