5.之前jianshu代码使用React-redux进行数据的管理19-06-06

代码见https://gitee.com/XiaoKunErGe/JianShu.git历史第五次提交
1.先安装
yarn add redux //数据框架
yarn add react-redux//方便我们在react中使用redux
安装后重启代码
2.创建store并创建index和reducer文件

import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
export default store;
const defaultState = {
  focused: false
};
export default (state = defaultState, action) => {
  return state;
}

3.在App里使用Provider,并引入store
import { Provider } from 'react-redux';
import store from './store';

function App() {
  return (
    
      
        
        
        
); }

4.引入connect
import {connect} from 'react-redux';
并将header与之关联
export default connect (mapStateToProps, mapDispatchToProps) (header);
在mapStateToProps中将store中的focused映射到props中

const mapStateToProps= (state)=>{
  return{
    focused:state.focused
  }
}
const mapDispatchToProps=(dispatch)=>{
  return{
}
}

删除constructor将所有this.state.focused换成this.props.focused
5.删除handleInputFocus和handleInputBlur方法
改写引用方法

 onFocus={this.props.handleInputFocus}
 onBlur={this.props.handleInputBlur}

并在mapDispatchToProps中实现方法

const mapDispatchToProps=(dispatch)=>{
  return{
    handleInputFocus(){
      const action = {
        type:'search_Focus'
      }
      dispatch(action);
    },
    handleInputBlur(){
      const action = {
        type: 'search_Blur'
      }
      dispatch(action);
    }
  }
}

并到reducer中处理数据,

export default (state = defaultState, action) => {
  if(action.type === 'search_Focus'){
     return{
       focused: true
     }
  }
  if(action.type === 'search_Blur'){
     return{
       focused: false
     }
  }
  return state;
}

就OK了
6.到header的index中class中只有一个render函数所以改写为无状态函数,提高性能。

const Header = (props) =>{
    return( )
}

组件中的所有代码复制进去,并将所有法人this.props改写成props就OK了。

你可能感兴趣的:(5.之前jianshu代码使用React-redux进行数据的管理19-06-06)