资源
各种进阶资源 + 联系方式请看下方链接
资源
redux使用场景及基本介绍
首先主页 redux 并不是只为react框架服务
- 单向数据流:从父组件流向子组件,兄弟组件无法共享数据
- state:react中的状态,是只读对象,不可直接修改
- reducer: 基本函数,用于对state的业务处理
- action:普通对象,用于描述事件行为 改变state
由上图可以看出 redux的工作流程是首先 例如 点击事件触发action 然后reducer加工 然后改变store store的改变会触发组件更新
redux集成
- 创建action模块 用来存放用户的行为
- 创建reducer模块 作为数据处理
- 创建store模块 存放数据初始状态
- 添加connect方法将react组件和redux连接起来
- 添加provider作为项目的根组件 用于数据的存储
redux调试工具安装
- 在Chrome中安装redux devtools
- 在代码里 yarn add redux-devtools-extension
- 必须两者都安装好才可以调试
- 在代码中安装redux react-redux
具体代码步骤
- 首先创建一个redux文件夹 里面创建好 action reducer store 文件夹
- 在action 文件夹中创建index.js 里面写
/*
* action 类型 例如你的是一个添加事件就用ADD_自定义名称
*/
export const type = {
SWITCH_MENU : 'SWITCH_MENU'
}
// 菜单点击切换,修改面包屑名称 这个方法里面有上面定义的类型和传递过来的值
export function switchMenu(menuName) {
return {
type:type.SWITCH_MENU,
menuName
}
}
- reducer中的index中写 对数据的处理函数
import { combineReducers } from 'redux'
import { type } from '../action';
const ebikeData = (state, action) => { //这里的形参是固定写法
switch (action.type) {
case type.SWITCH_MENU:
return {
...state, //把原有的状态保留
menuName:action.menuName //添加新的状态
};
default:
return {...state}; //默认状态
}
};
export default ebikeData;
4.store中的index存储了所有的状态
// 引入createStore创建数据源对象store,引入applyMiddleware 来使用中间件
import { createStore,applyMiddleware } from 'redux';
// 引入所有的reducer
import reducer from './../reducer';//reducer依赖action store依赖reducer
// 安装redux-devtools-extension的可视化工具。
import { composeWithDevTools } from 'redux-devtools-extension'
const initialState = {
menuName: '' //初始化的数据
}
const configureStore = () => createStore(reducer, initialState);
export default configureStore;
- 在入口文件中导入
import { Provider } from 'react-redux'
import configureStore from './redux/store/configureStore';
// Redux Store对象,管理所有的Redux状态
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<Router />
</Provider>,
document.getElementById('root')
);
- 在组件中点击改变store中的值
import { connect } from 'react-redux'
import { switchMenu} from './../../redux/action'
在最下面
export default connect()(当前组件名)
// 事件派发,自动调用reducer,通过reducer保存到store对象中 在事件中定义
const { dispatch } = this.props; //得先完成上一部
dispatch(switchMenu(item.props.title));
- 在需要根据store改变组件中的值的组件中使用
import { connect } from 'react-redux'
在render 中
const { menuName } = this.props;
//写完这个函数就可以在组件中使用this.props.menuName了
const mapStateToProps = state => {
return {
menuName: state.menuName
}
};
export default connect(mapStateToProps)(当前组件名)
在组件中就可以使用 menuName了