zoukankan      html  css  js  c++  java
  • xml ui

    useReducer may be used as an alternative to useState.

    const [state, dispatch] = useReducer(reducer, initialState, lazyInitFunction)
    

    Ideal for complex state logic where there's a dependency on previous state values or a lotta state sub values

    const initialState = {  15 }
    const reducer = (state, action) => {
      switch (action) {
        case 'plus':
          return {  state.width + 15 }
        case 'minus':
          return {  Math.max(state.width - 15, 2) }
        default:
          throw new Error("what's going on?" )
      }
    }
    
    const Bar = () => {
      const [state, dispatch] = useReducer(reducer, initialState)
      return <>
        <div style={{ background: 'teal', height: '30px',  state.width }}></div>
        <div style={{marginTop: '3rem'}}>
            <button onClick={() => dispatch('plus')}>Increase bar size</button>
            <button onClick={() => dispatch('minus')}>Decrease bar size</button>
        </div>
        </>
    }
    render(Bar)
    

    以lazy函数返回设置初始状态

    const initializeState = () => ({
       100
    })
    // ✅ note how the value returned from the fn above overrides initialState below: 
    const initialState = {  15 }
    const reducer = (state, action) => {
      switch (action) {
        case 'plus':
          return {  state.width + 15 }
        case 'minus':
          return {  Math.max(state.width - 15, 2) }
        default:
          throw new Error("what's going on?" )
      }
    }
    
    const Bar = () => {
      const [state, dispatch] = useReducer(reducer, initialState, initializeState)
      return <>
        <div style={{ background: 'teal', height: '30px',  state.width }}></div>
        <div style={{marginTop: '3rem'}}>
            <button onClick={() => dispatch('plus')}>Increase bar size</button>
            <button onClick={() => dispatch('minus')}>Decrease bar size</button>
        </div>
        </>
    }
    render(Bar)
    

    模拟this.setState的merge行为

    const initialState = {  15 }
    const reducer = (state, newState) => ({
      ...state,
       newState.width
    })
    
    const Bar = () => {
      const [state, setState] = useReducer(reducer, initialState)
      return <>
        <div style={{ background: 'teal', height: '30px',  state.width }}></div>
        <div style={{marginTop: '3rem'}}>
            <button onClick={() => setState({ 100})}>Increase bar size</button>
            <button onClick={() => setState({ 3})}>Decrease bar size</button>
        </div>
        </>
    }
    render(Bar)
    

    https://react-hooks-cheatsheet.com/

  • 相关阅读:
    独家干货!两种低代码模型驱动开发技术对比
    GeneXus低代码产品版本大更新,助力打造专业开发团队,加速企业数字化转型!
    企业级低代码平台应具备哪些要素?(下)
    如何选择低代码平台?GeneXus低代码平台
    C语言结构体的“继承”
    C语言实现wake on lan(网络唤醒)
    Linux驱动中的异步通知
    Linux网络设备驱动概述
    Linux下的广播程序
    DCMA86P2网卡成功显示802.11p
  • 原文地址:https://www.cnblogs.com/Searchor/p/13877937.html
Copyright © 2011-2022 走看看