日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

react如何獲取state的值并更新使用_React

作者:馬優(yōu)晨 ? 更新時(shí)間: 2022-10-02 編程語(yǔ)言

react獲取state值并更新使用

react獲取state的值并且修改分為兩種情況:

在視圖層處理

//在 state 中飯?jiān)O(shè)置初始值
state={
? ? ? name:'',
? ? ? age:''
?}
//通過(guò) 控制一個(gè)事件觸發(fā)然后setState 去設(shè)置
setName=()=>{
? ? this.setState({
? ? ? ?name
? ? })
}

在model層處理

view層

? //前端通過(guò)dispatch 去調(diào)用changeTab 接口
? onTabsChange = (key) => { ?
? ? this.props.dispatch({
? ? ? type: `${this.module}/changeTab`, ?
? ? ? payload: key
? ? });
? }

model層:

const moduleName = 'mayouchen';
let defaultState = {
? activeTabKey: "1"
};
export default {
? namespace: moduleName,
? state: {
? ? moduleName: moduleName,
? ? defaultState,
? ? ...defaultState
},
effects: {
?* changeTab({ payload, }, { call, put, select }) { ?
? ? ? ?// 更新 ?activeTabKey ?
? ? ? ?yield put({
? ? ? ? ?type:'updateActiveTabKey',
? ? ? ? ?payload
? ? ? ?});?
? ? ? // 更新完 ?activeTabKey ?就可以使用 ?activeTabKey 更新后的值
? ? ? ?yield put({type: 'getDataByTab'});
?},
? * getDataByTab({payload }, { call, put, select }) {?
? ? ? ? let { activeTabKey } = yield select(state => state[moduleName]);
? ? ? ? //切換TAB調(diào)用不同接口
? ? ? ? if(activeTabKey == "1") { ?//商戶信息
? ? ? ? ? yield put({type:'businessInformation', payload: {}});
? ? ? ? } else if (activeTabKey == "2" ) { ?//審批信息
? ? ? ? ? yield put({type:'approvalInformation', payload: {}})
? ? ? ? }else if (activeTabKey == "3" ) {
? ? ? ? }
? ? },?
? ?* businessInformation ({payload, }, { call, put, select }) {
? ? ?const result = yield call(read, payload);
? ? ?if (result ) {
? ? ? ?let { data } = result ;
? ? ? ?yield put({ type: 'getBusinessInformationData', payload: {...data }});
? ? ?}
? ? ?else {
? ? ? ?message.error(`獲取信息失敗:${entityRes.globalError}`);
? ? ?}
? }
}
?reducers: {
? ? ?updateActiveTabKey(state, action) {
? ? ? return {
? ? ? ? ...state,
? ? ? ? activeTabKey: action.payload
? ? ? };
? ? }
}

react中state基本使用

有狀態(tài)組件和無(wú)狀態(tài)組件

  • 函數(shù)組件又叫做 無(wú)狀態(tài)組件,類組件又叫做 有狀態(tài)組件
  • 狀態(tài)( state )即 數(shù)據(jù)
  • 函數(shù)組件沒(méi)有自己的狀態(tài),只負(fù)責(zé)數(shù)據(jù)展示(靜)
  • 類組件有自己的狀態(tài),負(fù)責(zé)更新Ul,讓頁(yè)面“動(dòng)”起來(lái)

比如計(jì)數(shù)器案例中,點(diǎn)擊按鈕讓數(shù)值加1。0和1就是不同時(shí)刻的狀態(tài),而由0變?yōu)?就表示狀態(tài)發(fā)生了變化。狀態(tài)變化后,UI也要相應(yīng)的更新。React中想要實(shí)現(xiàn)該功能,就要使用有狀態(tài)組件來(lái)完成。

state的基本使用

  • 狀態(tài)( state )即數(shù)據(jù),是組件內(nèi)部的私有數(shù)據(jù),只能在組件內(nèi)部使用
  • state的值是對(duì)象,表示一個(gè)組件中可以有多個(gè)數(shù)據(jù)
  • 通過(guò) this.state 來(lái)獲取狀態(tài)

class App extends React.Component {
    // constructor() {
    //     super()
    //     // 初始化state
    //     this.state = {
    //         count: 0
    //     }
    // }
    // 簡(jiǎn)化語(yǔ)法初始化state  【推薦】
    state = {
        count: 0,
    }
    render() {
        return(
            <div>
                <h1>計(jì)數(shù)器:{this.state.count}</h1>
            </div>
        )
    }
}
// 渲染組件
ReactDOM.render(<App />, document.getElementById("root"))

setState修改狀態(tài)

  • 狀態(tài)是可變的
  • 語(yǔ)法:this.setState({ 要修改的數(shù)據(jù) })
  • 注意:不要直接修改 state 中的值,這是錯(cuò)誤的!!!
  • setState() 作用:1. 修改state 2. 更新UI
  • 思想:數(shù)據(jù)驅(qū)動(dòng)視圖

class App extends React.Component {
    // 簡(jiǎn)化語(yǔ)法初始化state  【推薦】
    state = {
        count: 0,
    }
    render() {
        return(
            <div>
                <h1>計(jì)數(shù)器:{this.state.count}</h1>
                <button onClick = {() => {
                    this.setState({
                        count: this.state.count + 1
                    })
                }}>+1</button>
            </div>
        )
    }
}
// 渲染組件
ReactDOM.render(<App />, document.getElementById("root"))

從JSX中抽離事件處理程序

  • JSX中摻雜過(guò)多JS邏輯代碼,會(huì)顯得非常混亂
  • 推薦:將邏輯抽離到單獨(dú)的方法中,保證JSX結(jié)構(gòu)清晰

  • 原因:事件處理程序中 this的值為undefined
  • 希望:this 指向組件實(shí)例( render方法中的this即為組件實(shí)例)

事件綁定this指向

1. 箭頭函數(shù)

  • 利用箭頭函數(shù)自身不綁定 this 的特點(diǎn)
  • render() 方法中的 this 為組件實(shí)例,可以獲取到 setState()

2. Function.prototype.bind()

利用 ES5 中的 bind() 方法,將事件處理程序中的 this 與組件實(shí)例綁定到一起

class App extends React.Component {
    constructor() {
        super()
        this.state = {
            count: 0,
        }
        this.onIncrement = this.onIncrement.bind(this)
    }
    // 事件處理程序
    onIncrement() {
        console.log('事件處理程序中的this:', this)
        this.setState({
            count: this.state.count + 1
        })
    }
    render() {
        return(
            <div>
                <h1>計(jì)數(shù)器:{this.state.count}</h1>
                <button onClick = { this.onIncrement }>+1</button>
            </div>
        )
    }
}
// 渲染組件
ReactDOM.render(<App />, document.getElementById("root"))

3. class的實(shí)例方法

  • 利用 箭頭函數(shù) 形式的 class實(shí)例 方法
  • 注意∶該語(yǔ)法是實(shí)驗(yàn)性語(yǔ)法,但是,由于 babel 的存在可以直接使用

class App extends React.Component {
    state = {
        count: 0,
    }
        
    // 事件處理程序
    onIncrement = ()=> {
        console.log('事件處理程序中的this:', this)
        this.setState({
            count: this.state.count + 1
        })
    }
    render() {
        return(
            <div>
                <h1>計(jì)數(shù)器:{this.state.count}</h1>
                <button onClick = { this.onIncrement }>+1</button>
            </div>
        )
    }
}
// 渲染組件
ReactDOM.render(<App />, document.getElementById("root"))

原文鏈接:https://mayouchen.blog.csdn.net/article/details/80801802

欄目分類
最近更新