react 全局状态管理 redux的使用

redux为全局状态管理类似vuex

目录

redux官网

一、安装

 npm install redux

二、创建

三、修改

四、接受

五、拆分、合并

六、异步处理 redux-thunk 的使用

七、redux-promise的使用

八、async和await

九、react-redux  的使用

十、修改soter的属性值

十一、异步的完整代码


redux官网

入门 Redux | Redux 中文官网

一、安装

 npm install redux

二、创建

src下新建reaux文件夹内部新建store.js

import {
    createStore
} from 'redux'

const reducer = (state = {
    isShow: true
}, action) => {
    let newState = {
        ...state
    }
    switch (action.type) {
        case "true":
            newState.isShow = true
            return newState
        case "false":
            newState.isShow = false
            return newState
        default:
            return state
    }
}
const store = createStore(reducer)

export default store

三、修改

constructor(创建前生命周期)

constructor 销毁生命周期

 store.dispatch 需要修改的字段

import React, { Component } from 'react'
import store from '../../redux/store'
export default class home extends Component {
  constructor(props) {
    super(props)
    store.dispatch({
      type:'false'
    })
  }
  
  componentWillUnmount() {
    // 在组件即将被销毁前执行清理操作
    store.dispatch({
      type:'true'
    })
  }
  toIndex(){
    this.props.history.push('/')
  }
  render() {
    return (
      
) } }

四、接受

componentDidMount 组件挂载后

 store.getState()获取到的最新对象

import React, { Component } from 'react'
// HashRouter
import {Route,Redirect,Switch,BrowserRouter} from 'react-router-dom'
import Films from '../views/films'
import Home from '../views/home'
import NotFound from '../views/NotFound'
import Login from '../views/login'
import store from '../redux/store'
function isNext(){
  return true
}
export default class router extends Component {
  state = {
    type : true
  }
  componentDidMount(){
    store.subscribe(() =>{
      this.setState({
        type : store.getState().isShow
      })
    })
  }
  render() {
    return (
      
{this.state.type &&this.props.children} { return isNext()? : }}/> {/* 404组件 */}
) } }

五、拆分、合并

新建CmanagecRedux新建tabbarRedux.js

tabbarRedux.js

const TabbarReducer = (state = {
    isShow: true
}, action) => {
    let newState = {
        ...state
    }
    console.log(action);
    switch (action.type) {
        case "true":
            newState.isShow = true
            return newState
        case "false":
            newState.isShow = false
            return newState
        default:
            return state
    }
}
export default TabbarReducer

store.js

import {
    createStore,combineReducers
} from 'redux'
import TabbarReducer from './CmanagecRedux/tabbarRedux'

const reducer = combineReducers({
    TabbarReducer
})
const store = createStore(reducer)

export default store

使用

import React, { Component } from 'react'
// HashRouter
import {Route,Redirect,Switch,BrowserRouter} from 'react-router-dom'
import Films from '../views/films'
import Home from '../views/home'
import NotFound from '../views/NotFound'
import Login from '../views/login'
import store from '../redux/store'
function isNext(){
  return true
}
export default class router extends Component {
  state = {
    type : true
  }
  componentDidMount(){
    store.subscribe(() =>{
      this.setState({
        type : store.getState().TabbarReducer.isShow
      })
    })
  }
  render() {
    return (
      
{this.state.type &&this.props.children} { return isNext()? : }}/> {/* 404组件 */}
) } }

六、异步处理 redux-thunk 的使用

安装

npm i [email protected]

使用

引入applyMiddleware

使用 const store = createStore(reducer,applyMiddleware(reduxThunk))

同步使用createStore()

异步使用applyMiddleware        

import axios from 'axios'
// redux-thunk
function getLsit() {
   return (complete) =>{
    axios.get('./test.json').then(res => {
        complete({
            list:res.data.data.films,
            type: 'addLsit'
        })
      
    })
   }
}


export {
    getLsit
}


store.js代码
import {

    createStore,combineReducers,applyMiddleware

} from 'redux'

import TabbarReducer from './CmanagecRedux/tabbarRedux'

import ListReducer from './CmanagecRedux/list'

import * as reduxThunk from 'redux-thunk'



const reducer = combineReducers({

    TabbarReducer,ListReducer

})

const store = createStore(reducer,applyMiddleware(reduxThunk))



export default store

销毁(声明一下)

  var unsubsribe = store.subscribe(() =>{

            setList(store.getState().ListReducer.list)

        })

销毁的时候在销毁声明周期运行一次即可

import React, { useEffect, useState } from 'react'
import { useHistory } from 'react-router-dom'
import store  from '../../redux/store'
import {getLsit} from '../../redux/asynchronous/getData'

export default function Index() {
    const [list,setList] = useState(store.getState().ListReducer.list)
    useEffect(() =>{
        if(store.getState().ListReducer.list.length === 0){
            store.dispatch(getLsit())
        }else{
          
        }
        var unsubsribe = store.subscribe(() =>{
            setList(store.getState().ListReducer.list)
        }) 
        return () =>{
            unsubsribe()
        }
    },[])
    const history = useHistory()
   const  toSearch = () => {
    history.push("/search")
    setList([])
   }
  return (
    
{ list.map(item =>
  • {item.name}
  • ) }
    ) }

    七、redux-promise的使用

    安装

    npm i redux-promise

    function getLsit() {
        return  axios.get('./test.json').then(res => {
            return{
                list:res.data.data.films,
                type: 'addLsit'
            }
          
        })
     }
    
    
    storstore.js代码
    
    import {
        createStore,combineReducers,applyMiddleware
    } from 'redux'
    import TabbarReducer from './CmanagecRedux/tabbarRedux'
    import ListReducer from './CmanagecRedux/list'
    import  reduxThunk from 'redux-thunk'
    import reduxPromise from 'redux-promise'
    const reducer = combineReducers({
        TabbarReducer,ListReducer
    })
    const store = createStore(reducer,applyMiddleware(reduxThunk,reduxPromise))
    
    export default store

    八、async和await

    async function getLsit() {
         const  list = await axios.get('./test.json').then(res => {
            return{
                list:res.data.data.films,
                type: 'addLsit'
            }
          
        })
        return list
     }

    九、react-redux  的使用

    安装

    npm i react-redux  

    src - index.js这样写

    重点代码

    import {Provider} from 'react-redux'

    import store from "./redux/store";

    root.render(

       

           

               

           

        );

     
    import React from "react";
     
    import App from './router/index'
    import './index.css'
    import Tabbar from './views/Tabbar'
    import {Provider} from 'react-redux'
    import store from "./redux/store";
    import { createRoot } from 'react-dom/client';//更新后的写法
    const container = document.getElementById('root');
    const root = createRoot(container);
    root.render(
        
            
                
            
        );

    使用状态页面

    修改抛出方式、不要直接抛出

    import { connect } from 'react-redux'

    state为soter的参数

    export default connect((state) =>{

      return {

        isShow:state.TabbarReducer.isShow

      }

    })(router)

    使用

    this.props.isShow

    全部代码

    import React, { Component } from 'react'
    // HashRouter
    import {Route,Redirect,Switch,BrowserRouter} from 'react-router-dom'
    import Films from '../views/films'
    import Home from '../views/home'
    import NotFound from '../views/NotFound'
    import Login from '../views/login'
    import List from '../views/list/index'
    import Search from '../views/list/search'
    import { connect } from 'react-redux'
    function isNext(){
      return true
    }
     class router extends Component {
      componentDidMount(){
      }
      render() {
        return (
          
    {this.props.isShow &&this.props.children} { return isNext()? : }}/> {/* 404组件 */}
    ) } } export default connect((state) =>{ return { isShow:state.TabbarReducer.isShow } })(router)

    十、修改soter的属性值

    在redux - asynchronous 添加 isTabbarRedux.js

    
    
    function hide(){
        return {
           type:"false"
       }
    }
    
    function show(){
       return {
           type:"true"
       }
    }
    
    export {show,hide}

    使用页面引入:

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    import { hide,show } from '../../redux/asynchronous/isTabbarRedux';
    class home extends Component {
      constructor(props) {
        super(props)
       this.props.hide()
      }
      
      componentWillUnmount() {
        this.props.show()
        // 在组件即将被销毁前执行清理操作
        // store.dispatch({
        //   type:'true'
        // })
      }
      toIndex(){
        this.props.history.push('/')
      }
      render() {
        return (
          
    ) } } // connect内部有两个值第一个是属性,第二个是回调函数 export default connect(null,{ hide, show })(home)

    十一、异步的完整代码

    import React, { useEffect, useState } from 'react'
    import { useHistory } from 'react-router-dom'
    import {getLsit} from '../../redux/asynchronous/getData'
    import { connect } from 'react-redux'
    
     function Index(props) {
        const {getLsit,list} = props
        useEffect(() =>{
            if(list.length === 0){
                getLsit()
            }
        },[list,getLsit])
        const history = useHistory()
       const  toSearch = () => {
        history.push("/search")
       }
      return (
        
    { list.map(item =>
  • {item.name}
  • ) }
    ) } const mapStateToProps = (state) =>{ return { list:state.ListReducer.list } } const mapDispatchToProps = { getLsit } export default connect(mapStateToProps,mapDispatchToProps)(Index)

    你可能感兴趣的:(react.js,前端,javascript)