在项目中的更换 React Hooks 注意事项

React 官方有说建议使用Hooks来管理你的项目,不过React 也说过不会放弃Class,网上说了一堆Hooks的说法。但是都是复制粘贴居多。css

Hooks出了好一段时间了,我今天才去了解,谷歌上也给出了不少解决方案了。react

我先说说为何推荐使用Hooks?

其实hooks的这种写法也不是很新鲜的事,早在antd的官方文档(相似hooks的组件写法),哪里的文档案例就不是咱们通常人用的class写法,致使我不少时候都须要再改写一次。如今的文档已经由另外一我的管理了吧写法都改回了Class写法。redux

缘由很简单,由于写代码写少了不少。没有this,没有生命周期,不须要.bind(this),就这么简单。bash

在React Hooks 里面咱们只需记住两个经常使用的方法便可。useState,useEffect。用来管理自身状态使用的。antd

useState 看就知道使用状态,只是和之前的写法有出入的是react-router

const [state,setState] = useState(defaultValue);
复制代码

你要相似Get Set的东西给定义好。app

useEffect 你能够简单的当作 componentDidMountcomponentDidUpdatecomponentWillUnmount这样一个顺序的生命周期结合版。dom

上面的东西就不说了,本身百度或者谷歌,网上一堆那个计算器的例子。ide

React-Router 在Hooks 里面的使用

因为Hooks没有this这个概念,因此之前使用的this.props.history.push()this.props.history.goBack() 这些都没法使用了这类型的JS跳转。函数

在这里咱们须要一个第三方的库use-react-router

import useReactRouter from 'use-react-router';
const {history,location,match} = useReactRouter();
history.goBack()
history.push('')
复制代码

其余的Router用法和Route的如出一辙,没有改变。

Reducers 状态管理

这个确定是每一个React 都关心的一个点

store.js

import {createStore} from 'redux';
import reducer from './reducers';

export const store  = createStore(reducer);
复制代码

那reducers.js有什么呢?

const initialState = {
    counter: 0
}

export default function reducer(state = initialState,action){
    switch(action.type){
        case "INCREMENT":
            return {counter: state.counter+1}
        case "DECREMENT":
            return {counter: state.counter-1}
        default:
            return state;
    }
}
复制代码

若是使用react-redux

只要将component(也就是Counter)放在Provider以内,就能够在Counter里面读取Redux Store。 再用connect把Counter串在一块儿才能把store传抵。

在Hooks建议使用 Redux-React-Hooks

import * as React from 'react';
import {StoreContext} from 'redux-react-hook';
import ReactDOM from "react-dom";
import {store} from './store';
import Counter from './Counter';

ReactDOM.render(
  <StoreContext.Provider value={store}>
      <Counter name="Sara" />
  </StoreContext.Provider>, 
  document.getElementById("root")
);
复制代码

基本上除了Provider一个component及其props须要更改外,其余皆与react-redux的例子无异。

最大的更动,在Counter.js就能够看到,因为redux-react-hooks提供了useMappedState及useDispatch,链接Counter的代码能够大大简化。

import * as React from 'react';
import "./styles.css";
import {useMappedState,useDispatch} from 'redux-react-hook';

export default function Counter(props) {

    const counter = useMappedState(state=> state.counter);
    
    const dispatch = useDispatch();
    return (
        <div>
            <h1>
                Hello, {props.name}
                {counter} times
            </h1>
            <div>
                <button onClick={()=>dispatch({type:"INCREMENT"})}>Increment</button>
                <button onClick={()=>dispatch({type:"DECREMENT"})}>Decrement</button>
            </div>
        </div>
    );
}
复制代码

一个useMappedState,就扮演了mapStateToProps的角色,使用useDispatch,更能够直接于部件里使用dispatch,无需任何特殊函数。其中一个更明显的好处,在于Counter的props没有依赖任何Redux的功能,所以要写单元测试(Unit testing)就更为简单。

Hooks代码整体上会简洁不少!!可读性也很乐观

相关文章
相关标签/搜索