美文网首页
useReducer

useReducer

作者: 一土二月鸟 | 来源:发表于2020-08-12 22:34 被阅读0次
import React from 'react';
import ReactDOM from 'react-dom';
import { useReducer } from 'react';

const NAME_DETAIL = 'name_detail';
const NAME_DETAIL_DEMO = 'name_detail_demo';

const myReducer = (state, action) => {
  console.log(action, 'action')
  switch(action.Demotype) {
    case NAME_DETAIL : {
      return {
        name: 'ww'
      }
    }
    case NAME_DETAIL_DEMO : {
      return {
        name: 'dd'
      }
    }
    default: {
      return {
        name: 'pp'
      }
    }
  }
};

const Demo = () => {
  const initValue = {name: 'gaga'}; // 为state的初始值
  //  myReducer为dispatch的回调函数,只能通过dispatch才能触发myReducer
  const [ state, dispatch ] = useReducer(myReducer, initValue);

  const clickButton = () => {
    dispatch({
      type: NAME_DETAIL_DEMO
    });
  }

  return <> 
    i am demo {state.name}
    <button onClick={clickButton}>demo button</button>  
  </>;

}

const Test = () => {

  const [state, dispatch] = useReducer( myReducer, { name: 'wp' });

  const clickButton = () => {
    dispatch({
      type: NAME_DETAIL
    });
  };

  return <>
    {state.name} 
    <button onClick={clickButton}>click</button>
    <br/>
    <Demo></Demo>
  </>;
}

ReactDOM.render(<Test />, document.getElementById('root'));

相关文章

网友评论

      本文标题:useReducer

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