了解 react 新特性 hooks

了解 react 新特性 hooks

前言

在 React 中使用 class 继承 React.Component,就可以在类里面使用各种各样的钩子函数,比如 componentWillMount、componentDidMount、componentWillUnmount 等。你也可以直接写 function 来构建 reander 方法,但是就无法使用钩子函数,无法使用 setState 修改状态。在 React 16 版本之后新增了 hooks 特性,hooks 特性的主要表现形式为:在 React 中可以直接使用函数的形式来完成所有组件逻辑。

useState

useState 方法是用来修改数据状态。

import React,{useState} from 'react';
import ReactDOM from 'react-dom';
function App() {
    const [count,setCount]=useState(0);
    return <div onClick={setCount(count+1)}>
        {count}
    </div>
}
ReactDOM.render(<App />, document.getElementById('root'));

以上案例中没有使用 class 的形式,也没有继承 React.Component。但是可以使用 useState 来达到修改状态的目的。其中定义了 count 变量和 setCount 方法, useState 数组后面的元素是 count 的初始值,setCount 方法是修改状态,类似于 setState。

那么如果需要使用 componentDidMount 函数,调取接口数据怎么办呢?

useEffect

useEffect 方法是用来执行 DOM 挂载或者更新之后的事务。

import React,{useState,useEffect} from 'react';
import ReactDOM from 'react-dom';
function App() {
    const [users,setUsers]=useState({});
    useEffect(()=>{
    axios.get('/login').then(res=> {     
        setValues(users=> ({           
            users:res.data.result
        }));
    },{}) 
    return <div>{{users.name}} </div>
}
ReactDOM.render(<App />, document.getElementById('root'));

useEffect 方法可以替代 componentDidMount 和 componentDidUpdate。可以在 useEffect 中调取接口数据,然后更新 state。

useContext

useContext 方法是用来共享数据,跨组件传值。

import React,{useContext} from 'react';
import ReactDOM from 'react-dom';
function ShareContext() {
    const Context = React.creatContext({loading: false});
    return Context; 
}
import Context from 'ShareContext';
function Item() {
    const ctx = useContext( Context );
    return<div>
            {ctx.loading && ‘Loading...}
        </ div>}
function App() { 
    return<div>
            <Item/>
        </ div>}
ReactDOM.render(<App />, document.getElementById('root'));

useContext 方法与之前的 context 属性功能差不多,只不过写法要简洁很多。以上流程为:先写一个共享的 Context 数据,然后其他组件通过 useContext 方法获取组件中的值。但是这种方法只能共享状态,没法修改共享的状态,如果想要修改共享的状态可以使用 useReducer。类似于 Redxu 的功能。

useReducer

useReducer 用于复杂的状态管理。

import React,{useReducer} from 'react';
import ReactDOM from 'react-dom';
const initState = {count:0};
const reducer = (state,action)=>{
   switch(action.type){
   case 'add':
      return action.count++;
   case 'reduce':
      return action.count--;
   default:
      throw new Error();
   }
}
function App() {   
   const [ state, dispatch ] = useReducer(reducer,initState);
   return <div>
   <div>{state.count}</div>	
   <div onclick = dispatch({type:add})>+</div>
   <div onclick = dispatch({type:reduce})>-</div>
</div>	
}
ReactDOM.render(<App />, document.getElementById('root'));

useReducer 方法接收三个参数,第一个参数是修改 action 的 reducer,第二个参数是初始状态,第三个参数是useReducer 初始执行时被处理的 action。

发布了252 篇原创文章 · 获赞 2360 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_44135121/article/details/103156095
今日推荐