react --- redux使用

2021-03-19  本文已影响0人  再回首已落幕

react-redux
React插件,作用:方便在React项目中使用Redux

react-thunk
中间件,作用:支持异步action
一、安装插件

npm install --save react-redux
npm install --save redux-thunk

二、新建文件
新建store目录
新建文件
state.js(存放数据)

export default {
    pageTitle: '首页',
    infoList: []
}

reducer.js (它就是将来真正要用到的数据,我们将其统一放置在reducers.js文件)

// 工具函数,用于组织多个reducer,并返回reducer集合
import { combineReducers } from 'redux'
// 默认值
import defaultState from './state.js'

// 一个reducer就是一个函数
function pageTitle (state = defaultState.pageTitle, action) {
  // 不同的action有不同的处理逻辑
  switch (action.type) {
    case 'SET_PAGE_TITLE':
      return action.data
    default:
      return state
  }
}

function infoList (state = defaultState.infoList, action) {
    
  switch (action.type) {
    case 'SET_INFO_LIST':
      return action.data
    default:
      return state
  }
}

// 导出所有reducer
export default combineReducers({
    pageTitle,
    infoList
})

action.js(现在我们已经创建了reducer,但是还没有对应的action来操作它们,所以接下来就来编写action)

export function setPageTitle(data) {
  return (dispatch, getState) => {
    dispatch({ type: "SET_PAGE_TITLE", data: data });
  };
}
export function setInfoList(data) {
  return (dispatch, getState) => {
    dispatch({ type: "SET_INFO_LIST", data: data });
  };
}

index.js

import { createStore , applyMiddleware} from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';

const store = createStore(
    reducer,
    applyMiddleware(thunk)<Provider store={store}>
        <App />
      </Provider>
);

export default store;

三、使用
index.js

import store from "./store/index";
import { Provider } from "react-redux";
<Provider store={store}>
        <App />
</Provider>

组件

// Test.jsx
import React, { Component } from "react";
// connect方法的作用:将额外的props传递给组件,并返回新的组件,组件在该过程中不会受到影响
import { connect } from "react-redux";
// 引入action
import { setPageTitle, setInfoList } from "../store/action";
class redux extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentDidMount() {
    let { setPageTitle, setInfoList } = this.props;
    // 触发setPageTitle action
    setPageTitle("新的标题");
    // 触发setInfoList action
    setInfoList("6666");
  }
  render() {
    // 从props中解构store
    let { pageTitle, infoList } = this.props;
    console.log(pageTitle);
    // 使用store
    return (
      <div>
        <h1>{pageTitle}</h1>
        <h1>{infoList}</h1>
        {/* {infoList.length > 0 ? (
          <ul>
            {infoList.map((item, index) => {
              <li>{item.data}</li>;
            })}
          </ul>
        ) : null} */}
      </div>
    );
  }
}
// mapStateToProps:将state映射到组件的props中
const mapStateToProps = (state) => {
  return {
    pageTitle: state.pageTitle,
    infoList: state.infoList,
  };
};
// mapDispatchToProps:将dispatch映射到组件的props中
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    setPageTitle(data) {
      // 如果不懂这里的逻辑可查看前面对redux-thunk的介绍
      dispatch(setPageTitle(data));
      // 执行setPageTitle会返回一个函数
      // 这正是redux-thunk的所用之处:异步action
      // 上行代码相当于
      /*dispatch((dispatch, getState) => {
            dispatch({ type: 'SET_PAGE_TITLE', data: data })
        )*/
    },
    setInfoList(data) {
      dispatch(setInfoList(data));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(redux);
上一篇 下一篇

猜你喜欢

热点阅读