1. src 下的 common 下的 header 创建 store 文件夹 下创建 reducer.js
# src/common/header/store/reducer.js
const stateDefault = {
focused : false
};
export default (state = stateDefault, action)=>{
if(action.type === ‘focus‘ || action.type === ‘blur‘){
const newState = JSON.parse(JSON.stringify(state));
newState.focused = action.focused;
return newState;
}
return state;
}
2. 添加 redux-devtools-extension 拓展 并 创建 src/store/index.js 对 redux 数据进行监听
(未装 redux 拓展 , 使用 yarn add redux 进行安装)
yarn add redux-devtools-extension
# src/store/index.js
import { createStore ,compose, applyMiddleware } from ‘redux‘;
import reducer from ‘./reducer‘;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
applyMiddleware()
));
export default store;
3. 创建 src/store/reduct.js 使用 redux 的 对 header 的 reducer 数据进行管理
# src/store/reduct.js
import { combineReducers } from ‘redux‘;
import headerReducer from ‘../common/header/store‘;
export default combineReducers({
header : headerReducer
});
4. 修改 src/App.js 使 app 下的全部组件支持 store 数据存取
(未装 redux 拓展 , 使用 yarn add react-redux 进行安装)
#src/App.js
import React from ‘react‘;
import Header from ‘./common/header‘;
import store from ‘./store‘;
import {Provider} from ‘react-redux‘;
function App() {
return (
<div>
<Provider store={store}>
<Header />
</Provider>
</div>
);
}
export default App;
5. 修改 src/common/header/index.js 组件的引入路径
#src/common/header/index.js
import React from ‘react‘;
import {CSSTransition} from ‘react-transition-group‘;
import {connect} from ‘react-redux‘;
import {
HeaderWrapper,
Logo,
Nav,
NavItem,
SearchWrapper,
NavSearch,
Addtion,
Button
} from ‘./style‘;
const Header = (props)=>{
return (
<HeaderWrapper>
<Logo />
<Nav>
<NavItem className="left active">首页</NavItem>
<NavItem className="left">下载</NavItem>
<NavItem className="right">登陆</NavItem>
<NavItem className="right">
<span className="iconfont"></span>
</NavItem>
<SearchWrapper>
<CSSTransition
in={props.focused}
timeout={200}
classNames=‘slide‘
>
<NavSearch
className={props.focused? ‘focused‘ : ‘‘}
onFocus={props.searchFocus}
onBlur={props.searchBlur}
></NavSearch>
</CSSTransition>
<span className={props.focused? ‘focused iconfont‘ : ‘iconfont‘}></span>
</SearchWrapper>
</Nav>
<Addtion>
<Button className=‘writting‘>
<span className="iconfont"></span>
写文章
</Button>
<Button className=‘reg‘>注册</Button>
</Addtion>
</HeaderWrapper>
);
}
const PropsToState = (state)=>{
return {
focused : state.header.focused
}
}
const PropsToDispatch = (dispatch)=>{
return {
searchFocus(){
const action = {
type : ‘focus‘,
focused : true
}
dispatch(action);
},
searchBlur(){
const action = {
type : ‘blur‘,
focused : false
}
dispatch(action);
}
}
}
export default connect(PropsToState, PropsToDispatch)(Header);
原文地址:https://www.cnblogs.com/zonehoo/p/11984811.html