自定義useState

敲出真諦發表於2020-11-25

1.useState

import React, { useState} from 'react'


// 1.useState
export default function App() {
    const [state, setState] = useState({num:1});
    return(
        <div>
            <p>{state.num}</p>
            <button onClick={()=>setState({num: state.num+1})}>增加</button>
        </div>
    )
}

2. useReducer

mport React, { useReducer } from 'react'

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const initalState = {num: 0};
const reducer = (state, action) => {
    switch (action.type) {
        case INCREMENT:
            return { num: state.num + 1 };
        case DECREMENT:
            return { num: state.num - 1 };
        default:
            return state;
    }
}
export default function App() {
    const [state, dispatch] = useReducer(reducer, initalState);
    return (
        <div>
            <p>{state.num}</p>
            <button onClick={() => dispatch({ type: INCREMENT })}>增加</button>
            <button onClick={() => dispatch({ type: DECREMENT })}>減少</button>
        </div>
    )
}

3.自定義useState

import React, { useReducer, useCallback } from 'react'

const initalState = { num: 0 };
// 自定義useState
function useState(initalState) {
    const reducer = useCallback((state, action) => {
        console.log(action) // {payload:{num:1}}
        return action.payload
    })
    const [state, dispatch] = useReducer(reducer, initalState);
    function setState(payload) {
        console.log(payload) // {num: 0}
        dispatch({ payload })
    }

    return [state, setState]

}
export default function App() {
    // const [state, dispatch] = useReducer(reducer, initalState);
    const [state, setState] = useState(initalState);
    return (
        <div>
            <p>{state.num}</p>
            <button onClick={() => setState({ num: state.num + 1 })}>增加</button>
            <button onClick={() => setState({ num: state.num - 1 })}>減少</button>
        </div>
    )
}

 

相關文章