react怎么获取state的值并更新使用

发布时间:2022-08-08 11:14:28 作者:iii
来源:亿速云 阅读:400

这篇文章主要介绍“react怎么获取state的值并更新使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“react怎么获取state的值并更新使用”文章能帮助大家解决问题。

react获取state值并更新使用

react获取state的值并且修改分为两种情况:

在视图层处理

//在 state 中饭设置初始值
state={
      name:'',
      age:''
 }
//通过 控制一个事件触发然后setState 去设置
setName=()=>{
    this.setState({
       name
    })
}

在model层处理

view层

  //前端通过dispatch 去调用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调用不同接口
        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基本使用

有状态组件和无状态组件

比如计数器案例中,点击按钮让数值加1。0和1就是不同时刻的状态,而由0变为1就表示状态发生了变化。状态变化后,UI也要相应的更新。React中想要实现该功能,就要使用有状态组件来完成。

state的基本使用

react怎么获取state的值并更新使用

class App extends React.Component {
    // constructor() {
    //     super()
    //     // 初始化state
    //     this.state = {
    //         count: 0
    //     }
    // }
    // 简化语法初始化state  【推荐】
    state = {
        count: 0,
    }
    render() {
        return(
            <div>
                <h2>计数器:{this.state.count}</h2>
            </div>
        )
    }
}
// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

setState修改状态

react怎么获取state的值并更新使用

class App extends React.Component {
    // 简化语法初始化state  【推荐】
    state = {
        count: 0,
    }
    render() {
        return(
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick = {() => {
                    this.setState({
                        count: this.state.count + 1
                    })
                }}>+1</button>
            </div>
        )
    }
}
// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

从JSX中抽离事件处理程序

react怎么获取state的值并更新使用

事件绑定this指向

1. 箭头函数

react怎么获取state的值并更新使用

2. Function.prototype.bind()

利用 ES5 中的 bind() 方法,将事件处理程序中的 this 与组件实例绑定到一起

react怎么获取state的值并更新使用

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>
                <h2>计数器:{this.state.count}</h2>
                <button onClick = { this.onIncrement }>+1</button>
            </div>
        )
    }
}
// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

3. class的实例方法

react怎么获取state的值并更新使用

class App extends React.Component {
    state = {
        count: 0,
    }
        
    // 事件处理程序
    onIncrement = ()=> {
        console.log('事件处理程序中的this:', this)
        this.setState({
            count: this.state.count + 1
        })
    }
    render() {
        return(
            <div>
                <h2>计数器:{this.state.count}</h2>
                <button onClick = { this.onIncrement }>+1</button>
            </div>
        )
    }
}
// 渲染组件
ReactDOM.render(<App />, document.getElementById("root"))

关于“react怎么获取state的值并更新使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

推荐阅读:
  1. React中state和props
  2. props和state属性怎么在React 中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

react state

上一篇:学习Nodejs的目的有哪些

下一篇:PHP中的运算符如何使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》