React Native中使用redux

react-redux 文档 · Redux

whats redux

whats redux-toolkit

安装

npm install @reduxjs/toolkit react-redux

创建store

store下面添加两个文件

  • index.js 仓库的入口文件

  • reducer.js 创建初始状态,并导出一个函数

redux基础概念

Redux 是什么?

首先理解 “Redux” 是什么。它有什么作用?它帮助我解决什么问题?我为什么要使用它?

Redux 是一个使用叫做 “action” 的事件来管理和更新应用状态的模式和工具库 它以集中式 Store(centralized store)的方式对整个应用中使用的状态进行集中管理,其规则确保状态只能以可预测的方式更新。

为什么要使用 Redux?

Redux 帮你管理“全局”状态 - 应用程序中的很多组件都需要的状态。

Redux 提供的模式和工具使你更容易理解应用程序中的状态何时、何地、为什么、state 如何被更新,以及当这些更改发生时你的应用程序逻辑将如何表现. Redux 指导你编写可预测和可测试的代码,这有助于你确信你的应用程序将按预期工作。

我什么时候应该使用 Redux?

Redux 可帮助你处理共享状态的管理,但与任何工具一样,它也需要权衡利弊。使用 Redux 有更多的概念需要学习,还有更多的代码需要编写,需要添加了一些额外代码,并要求你遵循某些限制。这是短期和长期生产力之间的权衡。

在以下情况下使用 Redux:

  • 应用中有很多 state 在多个组件中需要使用

  • 应用 state 会随着时间的推移而频繁更新

  • 更新 state 的逻辑很复杂

  • 中型和大型代码量的应用,很多人协同开发

Redux Toolkit 是 Redux 官方强烈推荐,开箱即用的一个高效的 Redux 开发工具集。它旨在成为标准的 Redux 逻辑开发模式,我们强烈建议你使用它。

术语

Action

action 是一个具有 type 字段的普通 JavaScript 对象。你可以将 action 视为描述应用程序中发生了什么的事件.

const addTodoAction = {
  type: 'todos/todoAdded',
  payload: 'Buy milk'
}
Action Creator

action creator 是一个创建并返回一个 action 对象的函数。它的作用是让你不必每次都手动编写 action 对象:

const addTodo = text => {
  return {
    type: 'todos/todoAdded',
    payload: text
  }
}//这个addTodo就是一个action creator

Reducer

reducer 是一个函数,接收当前的 state 和一个 action 对象,必要时决定如何更新状态,并返回新状态。函数签名是:(state, action) => newState。 你可以将 reducer 视为一个事件监听器,它根据接收到的 action(事件)类型处理事件。

reducer 函数内部的逻辑通常遵循以下步骤:

  • 检查 reducer 是否关心这个 action

  • 如果是,则复制 state,使用新值更新 state 副本,然后返回新 state

  • 否则,返回原来的 state 不变

const initialState = { value: 0 }

function counterReducer(state = initialState, action) {
  // 检查 reducer 是否关心这个 action
  if (action.type === 'counter/increment') {
    // 如果是,复制 `state`
    return {
      ...state,
      // 使用新值更新 state 副本
      value: state.value + 1
    }
  }
  // 返回原来的 state 不变
  return state
}

Store

当前 Redux 应用的 state 存在于一个名为 store 的对象中。

store 是通过传入一个 reducer 来创建的,并且有一个名为 getState 的方法,它返回当前状态值:

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({ reducer: counterReducer })

console.log(store.getState())
// {value: 0}

Dispatch

Redux store 有一个方法叫 dispatch。更新 state 的唯一方法是调用 store.dispatch() 并传入一个 action 对象。 store 将执行所有 reducer 函数并计算出更新后的 state,调用 getState() 可以获取新 state。

store.dispatch({ type: 'counter/increment' })

console.log(store.getState())
// {value: 1}

**dispatch 一个 action 可以形象的理解为 "触发一个事件"**。发生了一些事情,我们希望 store 知道这件事。 Reducer 就像事件监听器一样,当它们收到关注的 action 后,它就会更新 state 作为响应。

dispath:传入action对象->作为参数传入初始化的reducer->进行判断更新

我们通常调用 action creator 来调用 action:

const increment = () => {
  return {
    type: 'counter/increment'
  }
}

store.dispatch(increment() //这里返回action对象)

console.log(store.getState())
// {value: 2}

Selector

Selector 函数可以从 store 状态树中提取指定的片段。随着应用变得越来越大,会遇到应用程序的不同部分需要读取相同的数据,selector 可以避免重复这样的读取逻辑:

const selectCounterValue = state => state.value

const currentValue = selectCounterValue(store.getState())
console.log(currentValue)
// 2

简单来说就是写一个函数返回状态量的一个元素

自学稀土掘金

Redux 最佳实践 Redux Toolkit 🔥🔥 - 掘金 (juejin.cn)

store的文件结构

  • 创建一个store文件夹

  • 创建一个index.ts做为主入口

  • 创建一个festures文件夹用来装所有的store

  • 创建一个counterSlice.ts文件,并导出简单的加减方法

最外层创建redux_component文件下,存放index.js用于写页面的UI

简单的加减1

store/index.js

import {configureStore} from 'redux/toolkit'

import counterSlice from './features/counterSlice'

const store = configureStore({
  reducer:
    counter:counterSlice
  }
})

export default store;

store/features/counterSlice.js

//导出简单的加减法运算
import {createSlice} from '@reduxjs/toolkit'


const initialState = {
  value:0,
  title:'redux toolkit pre'
}
//这里export是为了store文件中生成store
export  const counterSlice = createSlice({
  name:'counter',  //定义actions的头
  initialState,
  reducers:{ 
    //同时生成action:counter/increment
    increment:(state)=>{
      state.value+=1;
    },
    decrement:(state)=>{
      state.value-=1;
    }
  }
})


//这里调出的是actions对象 increment:'counter/increment'
export const {increment, decrement} = counterSlice.actions;

//调出reducers中加减的函数
export default counterSlice.reducer

app.js中全局调用

import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import Index from './redux_component/Index'

//STORE 引用
import { Provider } from 'react-redux';
import store from './store/index'
const App = ()=> {
  return (
      <Provider store={store}>
        <Index/>
      </Provider>
     
  )
}

export default App;

界面UI(redux_component/index.js)

import { StyleSheet, Text, View,Button } from 'react-native'
import React from 'react'

//引入相关hooks
import { useSelector,useDispatch } from 'react-redux'
//引入reducers中的相应方法
import { increment,decrement } from '../store/features/counterSlice'

const Index = ()=> {
  //通过useSelector直接拿到store中定义的value
  const {value} = useSelector((store)=>store.counter)
  //通过useDispatch 派发事件,传入action参数,不需要引入reducer
  const dispatch = useDispatch();
  return (
    <View>
      <Text>index</Text>
      <Text>{value}</Text>
      <Button title = "加" onPress={()=>{dispatch(increment())}}></Button>
      <Button title = "减" onPress={()=>{dispatch(decrement())}}></Button>
    </View>
  )
}

export default Index;
import { StyleSheet, Text, View,Button,TextInput } from 'react-native'
import React,{useState} from 'react'

//引入相关hooks
import { useSelector,useDispatch } from 'react-redux'
//引入reducers中的相应方法
import { increment,decrement } from '../store/features/counterSlice'

const Index = ()=> {
  //通过useSelector直接拿到store中定义的value
  const {value} = useSelector((store)=>store.counter)
  //通过useDispatch 派发事件
  const dispatch = useDispatch();
  const [amount,setAmount] = useState(1);
  return (
    <View>
      <Text>index</Text>
      <Text>{value}</Text>
      //这里setAmount的+是为了将输入input的字符出转变为整形
      <TextInput value = {amount} onChangeText = {(text)=>setAmount(+text)}  />
      <Button title = "加" onPress={()=>{dispatch(increment({value:amount}))}}></Button>
      <Button title = "减" onPress={()=>{dispatch(decrement())}}></Button>
    </View>
  )
}

export default Index;

传递参数达到想加(减)多少

import { StyleSheet, Text, View,Button,TextInput } from 'react-native'
import React,{useState} from 'react'

//引入相关hooks
import { useSelector,useDispatch } from 'react-redux'
//引入reducers中的相应方法
import { increment,decrement } from '../store/features/counterSlice'

const Index = ()=> {
  //通过useSelector直接拿到store中定义的value
  const {value} = useSelector((store)=>store.counter)
  //通过useDispatch 派发事件
  const dispatch = useDispatch();
  const [amount,setAmount] = useState(1);
  return (
    <View>
      <Text>index</Text>
      <Text>{value}</Text>
      //RN和react不同,rn使用text,react使用e/e.target.value
      <TextInput value = {amount} onChangeText = {(text)=>setAmount(+text)}  />
      <Button title = "加" onPress={()=>{dispatch(increment({value:amount}))}}></Button>
      <Button title = "减" onPress={()=>{dispatch(decrement())}}></Button>
    </View>
  )
}

export default Index;
console.log(increment());
//{"payload": undefined, "type": "counter/increment"}

我们可以看出来 这个increment() 是一个函数,返回一个对象包含两个字段,其实也就是action

那么他可以接受参数,payload,所以就是一个actionCreator

所以上面传入参数{value:amount}其实就是传入一个payload

//导出简单的加减法运算
import {createSlice} from '@reduxjs/toolkit'


const initialState = {
  value:0, 
  title:'redux toolkit pre'
}
//这里可以加export也可以不加
 const counterSlice = createSlice({
  name:'counter',  //定义actions的头
  initialState,  //state的初始值
  reducers:{ 
    //同时生成action:counter/increment
    //这里的payload就是action creator中返回的action中的payload
    increment:(state,{payload})=>{
      console.log(state);
      state.value+=payload.value //这里的value和上面value对应
    },
    decrement:(state)=>{
      state.value-=1;
    }
  }
})

console.log(counterSlice.reducer)

//这里调出的是actions对象 increment:'counter/increment'
export const {increment, decrement} = counterSlice.actions;

//调出reducers中加减的函数
export default counterSlice.reducer

接受传递的参数时,需要给reducers的函数第二个字段是action,包含type和payload,这里直接结构出payload,payload也是一个对象值为{value:"1"}

如何进行异步调用

createAsyncThunk 接收 2 个参数:

  • 将用作生成的 action 类型的前缀的字符串

  • 一个 “payload creator” 回调函数,它应该返回一个包含一些数据的 Promise,或者一个被拒绝的带有错误的 Promise

根据两个参数返回action

extraReducers

但是,有时 slice 的 reducer 需要响应 没有 定义到该 slice 的 reducers 字段中的 action。这个时候就需要使用 slice 中的 extraReducers 字段。

extraReducers 选项是一个接收名为 builder 的参数的函数。builder 对象提供了一些方法,让我们可以定义额外的 case reducer,这些 reducer 将响应在 slice 之外定义的 action。我们将使用 builder.addCase(actionCreator, reducer) 来处理异步 thunk dispatch 的每个 action。

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';


const initialState = {
  list: [],
  totals: 0
};

// 请求电影列表
const getMovieListApi = ()=> 
  fetch(
    'https://pcw-api.iqiyi.com/search/recommend/list?channel_id=1&data_type=1&mode=24&page_id=1&ret_num=48'
  ).then(res => res.json())

// thunk函数允许执行异步逻辑, 通常用于发出异步请求。
// createAsyncThunk 创建一个异步action,方法触发的时候会有三种状态:
// pending(进行中)、fulfilled(成功)、rejected(失败)
export const getMovieData = createAsyncThunk( 'movie/getMovie', 
  async () => {
    const res= await getMovieListApi();
    return res;
  }
);

// 创建一个 Slice 
export const movieSlice = createSlice({
  name: 'movie',
  initialState,
  reducers: {
    // 数据请求完触发
    loadDataEnd: (state, {payload}) => {
      state.list = payload;
      state.totals = payload.length;
    },
  },
  // extraReducers 字段让 slice 处理在别处定义的 actions, 
  // 包括由 createAsyncThunk 或其他slice生成的actions。
  extraReducers(builder) {
    builder
    .addCase(getMovieData.pending, (state) => {
      console.log("🚀 ~ 进行中!")
    })
    //这里的payload就是action creator中返回的action中的信息值
    .addCase(getMovieData.fulfilled, (state, {payload}) => {
      console.log("🚀 ~ fulfilled", payload);
      console.log(payload);
      state.list = payload.data.list
      state.totals = payload.data.list.length
    })
    .addCase(getMovieData.rejected, (state, err) => {
      console.log("🚀 ~ rejected", err)
    });
  },
});

// 导出方法
export const { loadDataEnd } = movieSlice.actions;

// 默认导出
export default movieSlice.reducer;
import { StyleSheet, Text, View,Button,TextInput } from 'react-native'
import React,{useState} from 'react'

//引入相关hooks
import { useSelector,useDispatch } from 'react-redux'
//引入reducers中的相应方法
import { increment,decrement } from '../store/features/counterSlice'
import { getMovieData } from '../store/features/movieSlice'
const Index = ()=> {
  //通过useSelector直接拿到store中定义的value
  const {value} = useSelector((store)=>store.counter)
  const {list} = useSelector((store)=>store.movie)
  //通过useDispatch 派发事件
  const dispatch = useDispatch();
  const [amount,setAmount] = useState(1);
  return (
    <View>
      <Text>index</Text>
      <Text>{value}</Text>
      <TextInput value = {amount} onChangeText = {(text)=>setAmount(+text)}  />
      <Button title = "加" onPress={()=>{dispatch(increment({value:amount}))}}></Button>
      <Button title = "减" onPress={()=>{dispatch(decrement())}}></Button>
//getMovieData是一个通过createAsyncThunk创建的action
      <Button title = "获取数据" onPress={()=>{dispatch(getMovieData())}}></Button>
      <View>
        {
          list.map((item)=>{return <Text key = {item.tvId} >{item.name} </Text>})
        }
      </View>
    </View>
  )
}

export default Index;

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
react-native-redux-router是一个用于在React Native应用管理路由和状态的库。它结合了React NativeReduxReact 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来管理路由和状态。你可以根据自己的需求进行扩展和定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值