溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

ReactNative狀態(tài)管理redux使用的方法是什么

發(fā)布時(shí)間:2023-03-10 09:52:30 來(lái)源:億速云 閱讀:97 作者:iii 欄目:開發(fā)技術(shù)

這篇“ReactNative狀態(tài)管理redux使用的方法是什么”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“ReactNative狀態(tài)管理redux使用的方法是什么”文章吧。

安裝和配置開發(fā)環(huán)境

安裝 Node.js 和 create-react-app 腳手架,用于快速創(chuàng)建 React 應(yīng)用程序

npx create-react-app playpage_ts -template typescript

安裝 React 和 Redux 關(guān)聯(lián)庫(kù) redux 和 react-redux

npm install @reduxjs/toolkit react-redux

定義數(shù)據(jù)結(jié)構(gòu)

這里我們假設(shè) TODO 就是一個(gè)文本

export type TODO = {
    text: string
}
//1.定義狀態(tài)數(shù)據(jù)
export type State = {
    todos: TODO[]
}
  • 定義行為 action,比如添加、刪除:

//2.定義行為
//action
export const ADD_TODO = 'ADD_TODO';
export const DELETE_TODO = 'DELETE_TODO';
//action creator
const ACTION_CREATOR_ADD_TODO = (text:string) => {
    return {type: ADD_TODO, payload: text}
};
const ACTION_CREATOR_DELETE_TODO = (text:string) => {
    return {type: DELETE_TODO, payload: text}
};
//分發(fā)數(shù)據(jù)變更操作,接收 store.dispatch
export function DISPATCH_ADD_TODO(dispatch: any) {
    return (text: string) => {
        dispatch(ACTION_CREATOR_ADD_TODO(text))
    }
}
export function DISPATCH_DELETE_TODO(dispatch: any) {
    return (text: string) => {
        dispatch(ACTION_CREATOR_DELETE_TODO(text))
    }
}

上面的代碼里,首先定義了行為類型( action type):ADD_TODO 和 DELETE_TODO,它們用于唯一標(biāo)識(shí)一個(gè)狀態(tài)改變行為。

然后創(chuàng)建了兩個(gè) action creator :ACTION_CREATOR_ADD_TODO 和 ACTION_CREATOR_DELETE_TODO,它們用于創(chuàng)建符合 reducer 約定的 action 對(duì)象,其中 type 標(biāo)識(shí)行為類型,payload 表示傳遞的數(shù)據(jù)。

最后創(chuàng)建了兩個(gè)函數(shù):DISPATCH_ADD_TODO 和 DISPATCH_DELETE_TODO,它們用于分發(fā)數(shù)據(jù)變更操作,簡(jiǎn)化后續(xù) connect 里的代碼。

然后創(chuàng)建行為處理函數(shù) todoReducer

import { State, TODO } from "./model";
import { ADD_TODO, DELETE_TODO } from "./todoActions";
const initState : State = {
    todos: [
        {
            text: "clean room"
        }
    ]
};
//3.創(chuàng)建行為處理函數(shù)
const todoReducer = (state: State = initState, action: any): State => {
    switch(action.type) {
        case ADD_TODO:
            //返回一個(gè)新的狀態(tài)樹
            return {
                todos: [...state.todos, {text: action.payload}]
            };
        case DELETE_TODO:
            console.log('todoReducer delete >>>' + action.payload)
            const todos = state.todos.filter((item: TODO, index: number)=> {
                return item.text != action.payload
            });
            return {
                todos
            }
        default:
            console.log('return default>>>' + JSON.stringify(state))
            return state;
    }
};
export default todoReducer;

todoReducer 的作用是根據(jù)行為,返回新的狀態(tài)。

參數(shù)是先前的狀態(tài) state 和要執(zhí)行的行為 action,根據(jù) action type 行為類型,返回不同的數(shù)據(jù)。

需要注意的是,reducer 中不能修改老數(shù)據(jù),只能新建一個(gè)數(shù)據(jù)。

  • 創(chuàng)建一個(gè) store,參數(shù)就是上面創(chuàng)建的行為處理函數(shù):

import { createStore } from 'redux';
import todoReducer from './reducers';
//4.創(chuàng)建 store,提供全局的狀態(tài)和行為處理
const store = createStore(
    todoReducer
);
//監(jiān)聽數(shù)據(jù)變化
store.subscribe( () => {
    console.log("store changed >>>" + JSON.stringify(store.getState()))
})
export default store;
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(
  rootReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
  • 分發(fā)給子元素:

import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import ReduxTodoApp from './ReduxTodoApp';
import store from './redux/store';
const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
//5.分發(fā)給子元素
root.render(
  <Provider store={store}>
    <ReduxTodoApp/>
  </Provider>
);

上面的代碼中,我們使用使用 react-redux 的 Provider 包圍了 App 組件,這樣整個(gè) App 組件都可以獲取到 Store 中的狀態(tài)和行為處理函數(shù)。

ReduxTodoApp 是下一步要?jiǎng)?chuàng)建的 UI 組件

創(chuàng)建 UI 組件:

import {useState} from "react";
import { connect } from "react-redux";
import { State, TODO } from "./redux/model";
import {DISPATCH_ADD_TODO, DISPATCH_DELETE_TODO } from "./redux/todoActions";
//6.數(shù)據(jù)和 action 函數(shù)需要通過(guò) prop 訪問(wèn)
function ReduxTodoApp (prop: {todos: TODO[], addTodo: any, deleteTodo: any}) {
    const {todos, addTodo, deleteTodo} = prop;
    const [text, setText] = useState('');
    const handleInput = (e: any) => {
        setText(e.target.value)
    }
    const handleAddTodo = () => {
        addTodo(text)
        setText('')
    }
    const handleDeleteTodo = (text: string) => {
        deleteTodo(text)
    }
    return (
        <div style={{display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center'}}>
            <h2>This Is Redux TODO App.</h2>
            <ul>
                {todos.map((todo: TODO, index: any) => {
                    return (
                        <li key={index}>
                            <span>{todo.text}</span>
                            <button style={{marginLeft: '12px'}} onClick={() => handleDeleteTodo(todo.text)}>finish</button>
                        </li>
                    )
                })}
            </ul>
            <div style={{display: 'flex', flexDirection: 'row'}}>
                <input value={text} onChange={handleInput}/>
                <button onClick={handleAddTodo}>Add Todo</button>
            </div>
        </div>
    )
}
//外部的數(shù)據(jù)(即state對(duì)象)如何轉(zhuǎn)換為 UI 組件的參數(shù)
//mapStateToProps會(huì)訂閱 Store,每當(dāng)state更新的時(shí)候,就會(huì)自動(dòng)執(zhí)行,重新計(jì)算 UI 組件的參數(shù),從而觸發(fā) UI 組件的重新渲染。
const mapStateToProps = (state: State) => {
    console.log('mapStateToProps >>> ' + JSON.stringify(state))
    //返回的是一個(gè)對(duì)象,需要根據(jù)屬性名訪問(wèn)
    return {
        todos: state.todos
    }   
}
//建立 UI 組件的參數(shù)到store.dispatch方法的映射
//定義了哪些用戶的操作應(yīng)該當(dāng)作 Action,傳給 Store
const mapDispatchToProps = (dispatch: any, ownProps: any) => {
    //返回一個(gè) Prop 對(duì)象
    return {
        addTodo: DISPATCH_ADD_TODO(dispatch),
        deleteTodo: DISPATCH_DELETE_TODO(dispatch)
    }
};
//5.組件接收數(shù)據(jù)和分發(fā)行為
export default connect(mapStateToProps, mapDispatchToProps) (ReduxTodoApp);

上面的代碼中,使用 connect 包裝了 UI 組件。

connect 的第一個(gè)參數(shù) mapStateToProps 用于返回當(dāng)前 UI 組件需要的數(shù)據(jù),這里我們獲取到 Store 中的 todos 列表。

第二個(gè)參數(shù) mapDispatchToProps 用于返回當(dāng)前 UI 組件需要向外分發(fā)的狀態(tài)操作行為,這里我們需要分發(fā)兩個(gè)行為:添加 todo 和刪除 todo,通過(guò)調(diào)用第二步中創(chuàng)建的 DISPATCH_ADD_TODO 和 DISPATCH_DELETE_TODO 實(shí)現(xiàn)。

正如名稱所示,mapStateToProps 和 mapDispatchToProps,最終都會(huì)向 Props 里添加成員。

這樣,我們的 UI 組件的 props 就會(huì)包含 mapStateToProps 中返回的狀態(tài)與 mapDispatchToProps 中的函數(shù),也就是這樣:

{
  todos: TODO[], 
  addTodo: any, 
  deleteTodo: any
}

注意名稱需要一致。

然后我們就可以在 UI 組件中通過(guò) prop.todos 獲取數(shù)據(jù),通過(guò) prop.addTodo 或者 prop.deleteTodo 通知修改數(shù)據(jù)。

總結(jié)一下,通過(guò)最原始的 redux 管理狀態(tài)分這幾步:

定義數(shù)據(jù)結(jié)構(gòu)類型,也就是前面的 State

  • 定義要進(jìn)行的數(shù)據(jù)修改行為 (action type),也就是前面的 ADD_TODO 和 DELETE_TODO

  • 然后創(chuàng)建 action creator,創(chuàng)建 reducer 里需要的 action 對(duì)象

  • 然后創(chuàng)建調(diào)用 store.dispatch 的函數(shù),簡(jiǎn)化 mapDispatchToProps 的代碼

有了行為后,然后就是處理行為,也就是 reducer

在其中根據(jù) action type,返回不同的狀態(tài)

有了 reducer 后,store 就齊全了,可以通過(guò) createStore 創(chuàng)建一個(gè)全局唯一的 store

通過(guò) react-redux 的 Provider 包裹整個(gè) app 組件,把 store 分發(fā)給所有組件

  • 最重要的一步:在 UI 組件里獲取數(shù)據(jù)和分發(fā)行為

  • 使用 react-redux 的 connect 包裹 UI 組件

  • connect 的第一個(gè)參數(shù)返回一個(gè)對(duì)象,在其中獲取 UI 組件里需要的數(shù)據(jù)

  • 第二個(gè)參數(shù)返回一個(gè)對(duì)象,其中包括要向外分發(fā)的行為

  • 在 UI 組件里通過(guò) props.xxx 的方式獲取數(shù)據(jù)和分發(fā)行為

步驟有些繁瑣,但重要的是,行為和行為處理都拆分開,及時(shí)業(yè)務(wù)變得復(fù)雜,后續(xù)拓展也比較輕松。

如果要分析某個(gè)狀態(tài)修改操作,在 reducer 里增加日志即可定位到,這就是 redux 宣稱的優(yōu)勢(shì):“可追溯”。

以上就是關(guān)于“ReactNative狀態(tài)管理redux使用的方法是什么”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI