美文网首页
React Hooks

React Hooks

作者: iCherries | 来源:发表于2020-02-23 17:32 被阅读0次

一.useState

// 新建文件,在 App.js 中引入
import React, { useState } from 'react'

const FruitList = ({ fruits, onSetFruit }) => {
    return (
        <ul>
            {fruits.map(item => <li key={item} onClick={() => onSetFruit(item)}>{item}</li>)}
        </ul>
    )
}

const FruitAdd = (props) => {
    const [name, setName] = useState('') // name: 变量, setName: 设置变量的方法

    const onAddFruit = e => {
        if (e.key === 'Enter') {
            props.onAddFruit(name)
            setName('')
        }
    }

    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                onKeyDown={onAddFruit}
            />
        </div>
    )
}

const HooksTest = () => {
    const [fruit, setFruit] = useState('')
    const [fruits, setFruits] = useState(['香蕉', '草莓', '芒果'])

    return (
        <div>
            <p>{fruit === '' ? '请选择喜爱的水果:' : `您的选择是: ${fruit}`}</p>
            <FruitList fruits={fruits} onSetFruit={setFruit} ></FruitList>
            <FruitAdd onAddFruit={name => setFruits([...fruits, name])} />
        </div>
    )
}

export default HooksTest;

提示: useState 最好是在最顶层调用, 组件每次渲染的 useState 数量必须要一致, 必须要完全相同的顺序调用. 推荐一个 eslint 用来检测 hooks 的包 (eslint-plugin-react-hooks)

// package.json 
"eslintConfig": {
    "extends": "react-app",
    "plugins": [
        "react-hooks"
    ],
    "rules": {
        "react-hooks/rules-of-hooks": "error"
    }
  },

二.useEffect

useEffect(() => { // 副作用操作保存: dom 操作, 定时器, ajax
    console.log(11111)
    return () => { // 相当于 componentWillUnmount 钩子
        console.log(222222)
    }
}, []) // 参数 2 指的依赖的状态, [] 中的值变化 useEffect 中的方法执行, 本案例只需执行一次,所以为空数组

三.useReducer

import React, { useState, useEffect, useReducer } from 'react'

const fruitReducer = (state, action) => {
    switch (action.type) {
        case 'init':
            return action.payload;
        case 'add':
            return [...state, action.payload];
        default: 
            return state;
    }
}

const FruitList = ({ fruits, onSetFruit }) => {
    return (
        <ul>
            {fruits.map(item => <li key={item} onClick={() => onSetFruit(item)}>{item}</li>)}
        </ul>
    )
}

const FruitAdd = (props) => {
    const [name, setName] = useState('')

    const onAddFruit = e => {
        if (e.key === 'Enter') {
            props.onAddFruit(name)
            setName('')
        }
    }

    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                onKeyDown={onAddFruit}
            />
        </div>
    )
}

const HooksTest = () => {
    const [fruit, setFruit] = useState('')
    // const [fruits, setFruits] = useState(['苹果', '橘子', '葡萄'])

    // 参数 1 是reducer
    // 参数 2 是初始值
    const [fruits, dispatch] = useReducer(fruitReducer, [])

    useEffect(() => {
        dispatch({ type: 'init', payload: ['苹果', '橘子']})
    }, [])

    return (
        <div>
            <p>{fruit === '' ? '请选择喜爱的水果:' : `您的选择是: ${fruit}`}</p>
            <FruitList fruits={fruits} onSetFruit={setFruit} ></FruitList>
            <FruitAdd onAddFruit={name => dispatch({ type: 'add', payload: name})} />
        </div>
    )
}

export default HooksTest;

四.useContext

import React, { useState, useEffect, useReducer, useContext } from 'react'

const Context = React.createContext()
const { Provider } = Context

const fruitReducer = (state, action) => {
    switch (action.type) {
        case 'init':
            return action.payload;
        case 'add':
            return [...state, action.payload];
        default:
            return state;
    }
}

const FruitList = ({ fruits, onSetFruit }) => {
    return (
        <ul>
            {fruits.map(item => <li key={item} onClick={() => onSetFruit(item)}>{item}</li>)}
        </ul>
    )
}

const FruitAdd = (props) => {
    const [name, setName] = useState('')
    const { dispatch } = useContext(Context)

    const onAddFruit = e => {
        if (e.key === 'Enter') {
            // props.onAddFruit(name)
            // setName('')
            dispatch({ type: 'add', payload: name })
            setName('')
        }
    }

    return (
        <div>
            <input
                type="text"
                value={name}
                onChange={e => setName(e.target.value)}
                onKeyDown={onAddFruit}
            />
        </div>
    )
}

const HooksTest = () => {
    const [fruit, setFruit] = useState('')
    // const [fruits, setFruits] = useState(['苹果', '橘子', '葡萄'])

    // 参数 1 是reducer
    // 参数 2 是初始值
    const [fruits, dispatch] = useReducer(fruitReducer, [])

    useEffect(() => {
        dispatch({ type: 'init', payload: ['苹果', '橘子'] })
    }, [])

    return (
        <Provider value={{ fruits, dispatch }}>
            <p>{fruit === '' ? '请选择喜爱的水果:' : `您的选择是: ${fruit}`}</p>
            <FruitList fruits={fruits} onSetFruit={setFruit} ></FruitList>
            <FruitAdd />
        </Provider>
    )
}

export default HooksTest;

相关文章

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • React Hooks

    前言 React Conf 2018 上 React 提出了关于 React Hooks 的提案,Hooks 作为...

  • 5分钟简单了解React-Hooks

    首先附上官网正文?:React Hooks Hooks are a new addition in React 1...

  • react-hooks

    react-hooks react-hooks 是react16.8以后,react新增的钩子API,目的是增加代...

  • React-hooks API介绍

    react-hooks HOOKS hooks概念在React Conf 2018被提出来,并将在未来的版本中被...

  • React Hooks 入门

    React Hooks 是 React v16.8 版本引入了全新的 API。 React Hooks 基本概念 ...

  • react hooks 源码分析 --- useState

    1. react hooks简介 react hooks 是react 16.8.0 的新增特性,它可以让你在不编...

  • React Hooks的入门简介

    什么是React Hooks? 首先React Hooks是React生态圈里的新特性,它改变了传统react的开...

  • React hooks(钩子)

    React hooks(钩子) React hooks 是React 16.8中的新增功能。它们使您无需编写类即可...

网友评论

      本文标题:React Hooks

      本文链接:https://www.haomeiwen.com/subject/ufxsqhtx.html