React项目便捷使用Redux管理状态
2019-07-15 11:35
1266 查看
最近公司里碰到需要使用redux解决公共状态的问题,查看了一下资料,来分享一下:
什么时候需要Redux?
当你遇到以下场景时,就可以引入redux了:
- 某个组件的状态,需要共享
- 某个状态需要在任何地方都可以拿到
- 一个组件需要改变全局状态
- 一个组件需要改变另一个组件的状态
如何引入Redux?
npm install redux --save
简易使用Redux
- 在项目文件下src中创建store文件夹,并在其中新建index.js文件
import { createStore } from 'redux' import reducer from './reducer'; const store = createStore(reducer); export default store;
- 在store文件夹下再新建reducer.js文件
const defaultState = { visible: false, List: [] } export default (state = defaultState, action) => { if (action.type === 'open_it') { const newState = JSON.parse(JSON.stringify(state)); newState.visible = action.value; return newState } return state; }
- 在需要引入store中的数据或者改变store中数据的地方引入
import store from './../store'
获取store中的state,并订阅store中的数据变化
constructor (props) { super(props) this.state = store.getState(); this.handleStoreChange = this.handleStoreChange.bind(this); store.subscribe(this.handleStoreChange) } handleStoreChange(){ this.setState(store.getState()); }
dispatch执行action
store.dispatch({ type: 'open_it', value: true });
Redux具体是什么,有什么高级使用?
这一块还是推荐大家看Redux官方文档以及阮一峰的redux相关博客
如果简单使用上面的例子就足够了
相关文章推荐
- Redux状态管理5 使用react-redux
- Redux状态管理 2.Redux如何和React一起使用
- React第三方组件5(状态管理之Redux的使用⑥Redux DevTools)
- React第三方组件5(状态管理之Redux的使用①简单使用)
- [置顶] React 项目中使用 MobX 进行状态管理
- React第三方组件5(状态管理之Redux的使用②TodoList上)
- 深入浅出React之第三章:使用redux管理应用状态
- React第三方组件5(状态管理之Redux的使用⑤异步操作)
- React第三方组件5(状态管理之Redux的使用④TodoList下)
- 使用Redux管理你的React应用
- redux 配合 react 在项目中的使用(个人总结与备忘)
- React第三方组件6(状态管理之Mobx的使用①简单使用)
- React第三方组件3(状态管理之Flux的使用⑤异步操作)
- React第三方组件6(状态管理之Mobx的使用⑤异步操作)
- 如何优雅地在React项目中使用Redux
- React第三方组件3(状态管理之Flux的使用②TodoList上)
- React第三方组件4(状态管理之Reflux的使用④TodoList下)
- react---redux状态管理
- 优雅的在React项目中使用Redux的方法
- react简书项目学习笔记30使用redux-immutabe统一数据格式