如何使用React Redux实现Tabs标签页切换的状态管理逻辑
React-Redux 实现标签页状态统一管理步骤
1. 安装依赖
首先安装redux和react-redux基础包:
npm install redux react-redux # 或使用yarn yarn add redux react-redux
2. 编写Redux核心逻辑
2.1 定义Tab相关Action
新建src/store/actions/tabActions.js文件:
// 定义action类型常量 export const SWITCH_TAB = 'SWITCH_TAB'; // 创建action生成函数,接收新的标签下标作为参数 export const switchTab = (tabValue) => { return { type: SWITCH_TAB, payload: tabValue } };
2.2 编写Tab对应的Reducer
新建src/store/reducers/tabReducer.js文件:
import { SWITCH_TAB } from '../actions/tabActions'; // 初始化状态,默认选中第一个标签 const initialState = { currentTab: 0 }; const tabReducer = (state = initialState, action) => { switch(action.type) { case SWITCH_TAB: // 返回新的状态,更新当前选中的标签值 return { ...state, currentTab: action.payload }; default: return state; } }; export default tabReducer;
2.3 创建全局Store
新建src/store/store.js文件:
import { createStore, combineReducers } from 'redux'; import tabReducer from './reducers/tabReducer'; // 合并reducer,后续新增业务状态可在此处扩展 const rootReducer = combineReducers({ tabState: tabReducer }); const store = createStore(rootReducer); export default store;
3. 修改入口文件注入Store
修改index.js,用Provider组件包裹App,让全局都能访问Redux状态:
import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; // 导入Provider和创建好的store import { Provider } from "react-redux"; import store from "./store/store"; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById("root"));
4. 改造App组件,替换本地状态为Redux状态
修改App.js,移除本地state,通过connect关联Redux状态和方法:
import { Component } from 'react'; import { connect } from 'react-redux'; import { switchTab } from './store/actions/tabActions'; class App extends Component { switchingTabs = (event, value) => { // 调用props中的redux方法,传递新的标签下标触发状态更新 this.props.switchTab(value); }; render() { // 从props中获取redux存储的当前选中标签值 const { currentTab } = this.props; return ( <div className="App"> <Container> <AppBar className="bar" position="static"> <Tabs value={currentTab} onChange={this.switchingTabs}> <Tab label="Commits Info"></Tab> <Tab label="User info"></Tab> </Tabs> </AppBar> <TabBackbone value={currentTab} index={0}></TabBackbone> <TabBackbone value={currentTab} index={1}></TabBackbone> <Content></Content> </Container> </div> ); } } // 将Redux中的状态映射到组件props const mapStateToProps = (state) => { return { currentTab: state.tabState.currentTab } }; // 将状态更新方法映射到组件props const mapDispatchToProps = (dispatch) => { return { switchTab: (value) => dispatch(switchTab(value)) } }; // 关联组件与Redux export default connect(mapStateToProps, mapDispatchToProps)(App);
流程说明
切换标签时,Tabs组件的onChange事件触发switchingTabs方法,调用props中的switchTab方法传递新的标签下标,该方法会派发action到reducer,reducer更新store中的currentTab值,store更新后自动同步到组件props,完成页面状态刷新。
内容的提问来源于stack exchange,提问作者evaldschukin
相关产品推荐
相关产品推荐

