Application react in redux + react-redux widget

First, download and install redux react-redux

npm install redux --save-dev

npm install react-redux --save-dev

 

 

 

1, first create a store of a folder (this is a public warehouse)

  And create a folder in the store store.js a file, a folder actions (this is an action instruction to be executed), reducer folder (this is a pure function)

  

 

 

 

2, the following code is written in the file store folder store.js of:

import {createStore,applyMiddleware} from "redux";
import reducer from "./reducer/reducer.js"; // this is purely a function of the introduced
import thunk from 'redux-thunk' // this is a middleware for asynchronous request
const store=createStore(reducer,applyMiddleware(thunk));
export default store;

 

3, the following code is written action.js store files in the folder in the folder actions:

import axios from "axios";
export default {
  handlePutback(){
    return {
      type: "PUTBACK", // This is the command sent
    }
  },
  handleGetCinemaDetail(id){
    return (dispatch) => {// perform asynchronous with the dispatch function
      var url_cinemaDetail="/v3/ajax/cinemaDetail?cinemaId="+id
      axios.get(url_cinemaDetail).then((res)=>{
        dispatch({
          type: "GETCINEMADETAIL", // This is the command sent
          This is axios back res // send data requested by the request
        })
      })
    }
  }
}

 

 

4, the following code is written in the store reducer.js file folder under the folder :( reducer of this package is a pure function of the total reducer)

import {combineReducers} from "redux";
import filmReducer from "./Film/filmReducer.js"; // this child of pure function
import cinemaReducer from "./Cinema/cinemaReducer.js"; // this child of pure function
import myReducer from "./My/myReducer.js"; // this child of pure function
import detailspageReducer from "./Detailspage/detailspageReducer.js"; // this child of pure function
const reducer=combineReducers({
  film: filmReducer,
  cinema:cinemaReducer,
  my:myReducer,
  detailspage:detailspageReducer,
})
export default reducer;

 

 

5, in the sub-reducer, the code is as follows:

var initState = {// This is used to initialize the data
  list: [],
  coming: [],
  Times: [],
  cinemas: localStorage.cinemas ? JSON.parse(localStorage.cinemas).cinemas : [],
  brand: {},
  district: {},
  Building type: {}
  service: {},
  subway: {},
  timeRanges {}
  who:{},
  cinemaTitle: localStorage.cinemaTitle ? JSON.parse(localStorage.cinemaTitle) : {},
  detailMovie:localStorage.detailMovie?JSON.parse(localStorage.detailMovie):{},
}
const reducer = (state = initState, actions) => {
  var newState = {... state} // initialization for copying data
  if (actions.type === "DATA") {// corresponding match, action, after the operation of the relative
    newState.list = actions.list;
  }
  if (actions.type === "DISPLAY") {
    newState.brand = actions.brand;
    localStorage.brand=JSON.stringify(newState.brand);
    newState.district = actions.district;
    localStorage.district=JSON.stringify(newState.district);
    newState.hallType = actions.hallType;
    localStorage.hallType=JSON.stringify(newState.hallType);
    newState.service = actions.service;
    localStorage.service=JSON.stringify(newState.service);
    newState.subway = actions.subway;
    localStorage.subway=JSON.stringify(newState.subway);
    newState.timeRanges = actions.timeRanges;
    localStorage.timeRanges=JSON.stringify(newState.timeRanges);
  }
  return newState
}
export default reducer;

 

6, then again you have to use the main page of the introduction of store you have created, the code is as follows:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import "./flexble.js"
import './index.css';
import store from "./store/store.js" // introduction store you created
import {Provider} from "react-redux" // store are connected by the react-redux Provider
ReactDOM.render(
  <Provider store = {store}> // wrapped after passing through the label and store
    <App />
  </Provider>
  , document.getElementById('root')
);

 

 

This will create a warehouse react finished it! ! !

 

 

 

 

7, the use of a common data store and functions in the formation method, the code is as follows:

import React, { Component } from 'react';
Widget import styled from 'styled-components' // react for style Gree
import action from "../../../store/reducer/Film/action"
import {connect} from "react-redux" // react-redux high order components
import Swiper from "swiper"
import 'swiper/dist/css/swiper.css'

class Show extends Component {
  componentDidMount() {
    this.props.handleData();
    this.props.handleTime();
  }
  componentDidUpdate() {
    new Swiper('.swiper-container', {
      freeMode: true,
      slidesPerView: 3,
      // autoplay:true,
      // loop:true,
    });
  }
  render() {
    return (
      <Div>
          {/ * Carousel navigation * /}
          <div className="show-lately">
            <P className = "show-title"> recently most anticipated </ p>
            <div className="swiper-container" >
            <div className="show swiper-wrapper">
            {
              this.props.com ? this.props.com.map((item, index) => {
              return <div className="swiper-slide" key={index}>
                <div className="show-content">
                  <div className="show-poster"><img src={item.img.slice(5,22)+148+"."+208+item.img.slice(25)} /><span>{item.wish}人想看</span></div>
                  <h5>{item.nm}</h5>
                  <p>{item.comingTitle}</p>
                </div>
               </div>
              }) : ""
            }
          </div>
        </div>
      </Div >
    );
  }
}
 
 
// mapped by the mapping store the data into the assembly and method
var mapState = (state) => {// mapped by the mapping of data to store in the component
  console.log(state.film.Times)
  return {
    com: state.film.coming.coming,
    time: state.film.Times
  }
}
var mapActions = (dispatch) => {// mapped by the mapping method is to store the components
  return {
    the handle data () {
      dispatch(action.getDatas())
    },
    handleTime() {
      dispatch(action.getTimes())
    }
  }
}
export default connect (mapState, mapActions) (Show); // react-redux high order components




const Div = styled.div` // ------------------ modify the style of similar less the same (note that you need to define a `` After this definition)
background:#f5f5f5;
height:100%;
width:100%;
position:absolute;
top:1.86rem;
// carousel navigation style
.show-lately{
padding: .2rem 0 .2rem .3rem;
background-color: #fff;
margin-bottom: .1rem;
overflow:hidden;
.show-title{
margin: 0 0 .2rem;
font-size: .3rem;
color: #333;
}
.swiper-container{
// display:initial;
.swiper-wrapper{
// overflow: scroll;
white-space: nowrap;
// display: initial;
.swiper-slide{
display: inherit;
width:auto;
.show-content{
display: inline-block;
// width: 2rem;
overflow: hidden;
margin-right: .1rem;
.show-poster{
width: 2rem;
height: 2.7rem;
position: relative;
margin-bottom: .1rem;
img{
width:100%;
height:100%;
}
span{
display: inline-block;
position: absolute;
left: .1rem;
bottom: .02rem;
color: #faaf00;
font-size: .2rem;
font-weight: 600
}
}
h5 {
margin: 0 0 .03rem;
font-size: .26rem;
color: #222;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
width:70%;
}
p{
margin: 0;
font-size: .24rem;
color: #999;
}
}
}
 
}
}
 
}
.show-list{
background:#fff;
.show-list-title{
padding: .2rem 0 0 .2rem;
font-size: .3rem;
color: #333;
}
.show-list-box{
display:flex;
align-items: center;
.list-img{
width: 1.4rem;
height:100%
margin-left:.2rem;
img{
width: 1.4rem;
height: 100%;
display: block;
}
}
.list-account {
justify-content:space-between;
display:flex;
width: 70%;
border-bottom: 1px solid #e6e6e6;
padding: .2rem 0 .2rem .1rem;
.list-cont-l{
padding:.1rem .2rem;
width:70%;
.list-left-t{
margin-bottom: .07rem;
display:flex;
align-items: center;
span:nth-of-type(1){
width:60%;
font-size:.4rem;
color: #333;
font-weight: 700;
padding-right:.1rem;
flex-shrink: 1;
display:inline-block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
span:nth-of-type(2){
border:1px solid #3c9fe6;
width: 1.1rem;
height: .35rem;
border-radius: .1rem;
background: #f4f4f4;
color: #3c9fe6;
}
}
.list-left-b{
color:#666;
font-size:.32rem;
div:nth-of-type(1){
span{
font-weight: 700;
color: #faaf00;
font-size: .34rem;
margin-left:.1rem;
}
}
div:nth-of-type(2){
width:90%;
margin-top:.1rem;
span{
display: inline-block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
}
}
div:nth-of-type(3){
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
width: 90%;
}
}
}
.list-cont-r{
width:20%;
position: relative;
right:.4rem;
span{
position:absolute;
top: 0;
bottom: 0;
margin: auto;
left: 0;
display: inline-table;
// background:#3c9fe6;
background:red;
width: 1.1rem;
height: .6rem;
line-height:.6rem;
text-align:center;
border-radius: .1rem;
color: #fff;
cursor: pointer;
}
}
}
}
}
}
`

 

 

 

 

react-redux works as follows, for a better understanding

 

 

 

Redux three principles

    • Throughout a single data source in a state the application is in the Object tree, and only exists in a unique stored Store.

    • read-only state is the only way is to change the state trigger action, action is a common description of the object for events, view only part of the expression of intent you want to modify, all changes will be centralized processing.

    • The use of pure function to perform the modification in order to achieve modify the state value based action, we need to write Reducer. It is purely a function of, the previous state and received new action returns state, increases with the application, you can break it into a plurality of small the Reducer, which are independent of the operation of different portions of state Tree.

 

 

 

2. specific work steps

 

 

 

 

Action

const add =()=>{ return { type:"add", data:id, } }

Is a function to return the upper Action, it is an object of the type and data contained. Action role is to tell the state what kind of operation manager needs to be done, as the above example is to add a message, thus defines a Action, and the data is what you need to do this operation data.

Reducer

reducer is a function of (pure function), to accept the old state and action, to make different operations depending on the Action and returns the new state. which is:(state, action) => state

const reducer = (state,action)=>{ switch(action.type){ case "add": state['newItemId'] = action.data; return {...state}; case "delete": delete state.newItemId; return {...state}; default : return state; } }

In the absence of any action case, state and original state that we return to the same.

Store

import { createStore } from 'redux'; const store = createStore(reducer);

This is the store, the object used to manage a single state in which there are three methods:

  • store.getState(): Get State, as described above, after a new reducer State returned, this function can be acquired.

  • store.dispatch(action): Issued action, for triggering reducer update state,

  • store.subscribe(listener):监听变化,当 state 发生变化时,就可以在这个函数的回调中监听。

React-Redux

Redux 官方提供的 React 绑定库。

容器组件与傻瓜组件

在应用中,通常容器组件对于 Redux 可知,他们的子组件应该是"傻瓜的"(傻瓜组件),并且通过porps获取数据。 容器组件: 通过组件 state 属性维护自身及其子组件的数据,它可以向 Redux 发起 action ,从 Redux 获取 新state值。 傻瓜组件: 通过 props 调用回调函数,从 props 获取数据展示。

注入 Store

import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { Provide } from 'react-redux'; import reducer from './reducer'; import App from './app'; const store = createStore(reducer); class RootComp extends React.Component{ render(){ //... return (//将整个视图结构包进 Provider <Provider store={store}> <App/> </Provider> ) } } ReactDOM.render(<RootComp/> ,document.getElementById('root'));

connect#

该方法用于从 UI 组件生成容器组件,

import React from 'react'; import { connect } from 'react-redux'; import Home from './home'; class AppContainer extends React.Component{ render( return ( <Home/> ); ) } const App = connect()(AppContainer);//这里的App就是生成的容器组件。 export default App;

connect( mapStateToProps , mapDispatchToProps , mergeProps , options )();

连接 React 组件与 Redux Store

  • mapStateToProps 该参数为一个 function mapStateToProps (state,[ownProps]){...},定义该参数后组件就可以监听 Redux Store 的变化,任何时候只要store发生变化,该函数就会被调用,该函数必须返回一个纯对象,它会与组件的 props 结合,而第二个参数 ownProps 被指定时,它代表传递到该组件的props,且只要组件收到新的 props ,mapStateToProps 就被调用。

  • mapDispatchToProps 通常我们会将该参数省略,此时默认情况下,dispatch 会注入到组件的props中,在你需要出发 action 的地方(可能是某个事件函数)使用该disaptch 函数将 action 发出。

例子:

在上边例子中,我们只要点击下添加链接,组件就会通过点击事件触发 dispath 函数 发送 action 到 store 中的 reducer, reducer 则根据 action 的 type 来决定执行什么操作,之后在 store 中新增一条记录(newItemId)后返回一个新的 state (里边包含Store中发生改变后的所有值),由于组件使用 connect 将自己与 Store 绑定起来,Store 中的值发生变化就会执行 mapStateToProps,将新的 state 放入组件的 props,从而引发组件的渲染。

Guess you like

Origin www.cnblogs.com/dongyuezhuang/p/11640151.html