React学习笔记之redux与react-redux

前言

React学习笔记系列仅为个人学习React后的代码总结,用于巩固与记录些重点知识,详细视频资源请参考bilibili:尚硅谷2021版React技术全家桶全套完整版(零基础入门到精通/男神天禹老师亲授)

安装

// 安装redux
 npm install redux  
 // 安装支持异步Action的中间件redux-thunk
 npm install redux-thunk
 // 安装react-redux
 npm install redux-thunk

redux使用

redux是一个专门用于做状态管理的JS库(不是react插件库),它可以用在react, angular, vue等项目中, 但基本与react配合使用,作用是集中式管理react应用中多个组件共享的状态。

原理

在这里插入图片描述
在src下新建redux文件夹,在redux下新建constant.js、count_action.js、count_reducer.js以及store.js,详细代码如下:

定义静态变量constant.js

export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

实现ActionCreators(count_action.js)

import {INCREMENT,DECREMENT} from './constant'

// 同步Action
export const Increment = data => ({type:INCREMENT,data})
export const Decrement = data => ({type:DECREMENT,data})
// 异步Action
export const IncrementAsync = (data,time) => {
    return (dispatch) => {
        setTimeout(()=>{
          dispatch(Increment(data))
        },time)
    }
}

实现Store(store.js)

import {createStore,applyMiddleware} from 'redux'
import countReducer from './count_reducer'
import thunk from 'redux-thunk'
// 用于支持异步Action需要applyMiddleware和thunk
export default createStore(countReducer,applyMiddleware(thunk))

实现Reducers(count_reducer.js)

 import {INCREMENT,DECREMENT} from './constant'

//  用于初始化
 const initState = 0
 export default function countReducer(preState = initState,action){
    const {type,data} = action
    switch (type) {
        case INCREMENT:           
          return preState + data;
        case DECREMENT:           
          return preState - data;
        default:
          return preState;
    }
 }

实现Count组件

在src下新建component,在component下新建Count,然后在Count下新建index.js

 import React, { Component } from 'react'
import store from '../../redux/store'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'

export default class Count extends Component {

    increment = () =>{
      const {value} = this.selectNumber
      store.dispatch(Increment(value*1))
    }
    decrement = () =>{
      const {value} = this.selectNumber
      store.dispatch(Decrement(value*1))

    }
    incrementIFOdd = () =>{
      const {value} = this.selectNumber
      if (store.getState() % 2 !== 0) {
        store.dispatch(Increment(value*1))
      }
    }
    incrementAsync = () =>{
      const {value} = this.selectNumber
      store.dispatch(IncrementAsync(value*1,500))
    }
    render() {
        return (
            <div>
              <h1>当前求和为:{store.getState()}</h1>
              <select ref={c => this.selectNumber = c}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
              </select>&nbsp;
              <button onClick = {this.increment}>+</button>&nbsp;
              <button onClick = {this.decrement}>-</button>&nbsp;
              <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
              <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
            </div>
        )
    }
}

App.js

import React, { Component } from 'react'
import Count from './components/Count'
import store from './redux/store'

export default class App extends Component {
    render() {
        return (
            <div>
              <Count/>
            </div>
        )
    }
}

程序入口index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'

ReactDOM.render(<App/>,document.getElementById('root'))

//用于当redux内的state更新时重新渲染界面的
store.subscribe(()=>{
    ReactDOM.render(<App/>,document.getElementById('root'))
})

react-redux使用

原理

在这里插入图片描述redux的代码无需改变,使用react-redux后无需再使用store.subscribe去监听redux的状态了,其中使用的connect将自动去监听,且无需为每个容器组件都提供store,可以使用react-redux提供的Provider去批量的给所有的容器组件传递store。

程序入口index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
import {Provider} from 'react-redux'

ReactDOM.render(
  <Provider store = {store}>
    <App/>
  </Provider>,
  document.getElementById('root')
)

// store.subscribe(()=>{
//     ReactDOM.render(<App/>,document.getElementById('root'))
// })

容器组件(container->Count->index.js)

在src下新建container->Count->index.js

import CountUI from '../../components/Count'
import {connect} from 'react-redux'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'

// mapStateToProps函数返回对象中的key就是作为传递给UI组件props的key,value就作为传递UI组件props的value----状态
// mapStateToProps函数是由redux帮我们调的并且已经执行getState(),除此之外还将其返回值传给mapStateToProps (state)
function mapStateToProps (state) {
    return {count: state}
}
// mapDispatchToProps传递操作状态的函数
function mapDispatchToProps (dispatch) {
    return {
      increment: (number) => {
        dispatch(Increment(number))
      },
      decrement: (number) => {
        dispatch(Decrement(number))
      },
      incrementAsync: (number,time) => {
        dispatch(IncrementAsync(number,time))
      }
    }
}

// 容器组件与UI组件建立联系并暴露
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)

UI组件(component->Count->index.js)

import React, { Component } from 'react'

export default class Count extends Component {

    increment = () =>{
      const {value} = this.selectNumber
      this.props.increment(value*1)
    }
    decrement = () =>{
      const {value} = this.selectNumber
      this.props.decrement(value*1)

    }
    incrementIFOdd = () =>{
      const {value} = this.selectNumber
      if (this.props.count % 2 !== 0) {
        this.props.increment(value*1)
      }
    }
    incrementAsync = () =>{
      const {value} = this.selectNumber
      this.props.incrementAsync(value*1,500)
    }
    render() {
        return (
            <div>
              <h1>当前求和为:{this.props.count} </h1>
              <select ref={c => this.selectNumber = c}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
              </select>&nbsp;
              <button onClick = {this.increment}>+</button>&nbsp;
              <button onClick = {this.decrement}>-</button>&nbsp;
              <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
              <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
            </div>
        )
    }
}

App.js

import React, { Component } from 'react'
import Count from './containers/Count'

export default class App extends Component {
    render() {
        return (
            <div>
              <Count/>
            </div>
        )
    }
}

mapDispatchToProps简写

原因是因为Increment等是一个含参数的函数,且react-redux将会实现自动分发(dispatch),总结mapDispatchToProps即可是一个函数,也可是个对象。

{
increment:Increment,
decrement:Decrement,
incrementAsync:IncrementAsync,
}

合并容器组件与UI组件

将component->Count->index.js整合到container->Count->index.js,原因是如果将组件分为容器与UI那么当组件个数多的时候将成倍增长导致项目文件过多。

合并后的container->Count->index.js

import {connect} from 'react-redux'
import {
    Increment,
    Decrement,
    IncrementAsync
} from '../../redux/count_action'
import React, { Component } from 'react'

class Count extends Component {

  increment = () =>{
    const {value} = this.selectNumber
    this.props.increment(value*1)
  }
  decrement = () =>{
    const {value} = this.selectNumber
    this.props.decrement(value*1)

  }
  incrementIFOdd = () =>{
    const {value} = this.selectNumber
    if (this.props.count % 2 !== 0) {
      this.props.increment(value*1)
    }
  }
  incrementAsync = () =>{
    const {value} = this.selectNumber
    this.props.incrementAsync(value*1,500)
  }
  render() {
      return (
          <div>
            <h1>当前求和为:{this.props.count} </h1>
            <select ref={c => this.selectNumber = c}>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
            </select>&nbsp;
            <button onClick = {this.increment}>+</button>&nbsp;
            <button onClick = {this.decrement}>-</button>&nbsp;
            <button onClick = {this.incrementIFOdd}>当前求和为奇数再加</button>&nbsp;
            <button onClick = {this.incrementAsync}>异步加</button>&nbsp;
          </div>
      )
  }
}


// mapStateToProps函数返回对象中的key就是作为传递给UI组件props的key,value就作为传递UI组件props的value----状态
// mapStateToProps函数是由redux帮我们调的并且已经执行getState(),除此之外还将其返回值传给mapStateToProps (state)
function mapStateToProps (state) {
    return {count: state}
}

function mapDispatchToProps (dispatch) {
    return {
      increment: (number) => {
        dispatch(Increment(number))
      },
      decrement: (number) => {
        dispatch(Decrement(number))
      },
      incrementAsync: (number,time) => {
        dispatch(IncrementAsync(number,time))
      }
    }
}

// 容器组件与UI组件建立联系并暴露
export default connect(mapStateToProps,mapDispatchToProps)(Count)
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
react-native-redux-router是一个用于在React Native应用中管理路由和状态的库。它结合了React Native、ReduxReact Navigation,提供了一种方便的方式来处理应用程序的导航和状态管理。 下面是一个简单的示例,演示了如何在React Native应用中使用react-native-redux-router: 1. 首先,安装所需的依赖项。在终端中运行以下命令: ```shell npm install react-native react-redux redux react-navigation react-native-router-flux --save ``` 2. 创建一个Redux store,并将其与React Native应用程序的根组件连接起来。在App.js文件中,添加以下代码: ```javascript import React from 'react'; import { Provider } from 'react-redux'; import { createStore } from 'redux'; import rootReducer from './reducers'; import AppNavigator from './navigation/AppNavigator'; const store = createStore(rootReducer); export default function App() { return ( <Provider store={store}> <AppNavigator /> </Provider> ); } ``` 3. 创建一个导航器组件,并定义应用程序的导航结构。在navigation/AppNavigator.js文件中,添加以下代码: ```javascript import { createAppContainer } from 'react-navigation'; import { createStackNavigator } from 'react-navigation-stack'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Actions } from 'react-native-router-flux'; import HomeScreen from '../screens/HomeScreen'; import DetailsScreen from '../screens/DetailsScreen'; const MainNavigator = createStackNavigator({ Home: { screen: HomeScreen }, Details: { screen: DetailsScreen }, }); const AppNavigator = createAppContainer(MainNavigator); const mapStateToProps = state => ({ // 将Redux状态映射到导航器组件的props中 }); const mapDispatchToProps = dispatch => bindActionCreators(Actions, dispatch); export default connect(mapStateToProps, mapDispatchToProps)(AppNavigator); ``` 4. 创建屏幕组件,并在其中使用导航和Redux状态。在screens/HomeScreen.js文件中,添加以下代码: ```javascript import React from 'react'; import { View, Text, Button } from 'react-native'; import { Actions } from 'react-native-router-flux'; const HomeScreen = () => { return ( <View> <Text>Welcome to the Home Screen!</Text> <Button title="Go to Details" onPress={() => Actions.details()} /> </View> ); } export default HomeScreen; ``` 5. 创建其他屏幕组件,并在其中使用导航和Redux状态。在screens/DetailsScreen.js文件中,添加以下代码: ```javascript import React from 'react'; import { View, Text, Button } from 'react-native'; import { Actions } from 'react-native-router-flux'; const DetailsScreen = () => { return ( <View> <Text>Welcome to the Details Screen!</Text> <Button title="Go back" onPress={() => Actions.pop()} /> </View> ); } export default DetailsScreen; ``` 这是一个简单的示例,演示了如何在React Native应用中使用react-native-redux-router来管理路由和状态。你可以根据自己的需求进行扩展和定制。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值