Skip to content

useReducer的使用

司徒正美 edited this page Dec 21, 2018 · 1 revision
<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<!--
<script src="https://cdn.bootcss.com/react/16.7.0-alpha.2/umd/react.development.js"></script>
  <script src="./react-dom.development.js"></script>
-->
 <script src="./dist/React.js"></script>

	<script type='text/javascript' src="./lib/babel.js"></script>

</head>

<body>

	<div id='root' class="root">

	</div>
	<script type='text/babel'>
        
var container = document.getElementById('root');
  var div = container;
  if (!window.ReactDOM) {
      window.ReactDOM = React;
  }
  var expect = function(a) {
      return {
          toBe: function(b) {
              console.log(a, 'vs', b, a === b);
          },
          toEqual(b) {
              console.log(a, 'vs', b, a + '' === b + '');
          },
          toThrow(){
              try{
                  a()
              }catch(e){
                  console.log(e,"catch")
              }
          }
      };
};
var {useState, useEffect,useReducer, useRef} = React;
const initialState = {count: 0};

function reducer(state, action) {
  switch (action.type) {
    case 'reset':
      return initialState;
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      // A reducer must always return a valid state.
      // Alternatively you can throw an error if an invalid action is dispatched.
      return state;
  }
}

function Counter({initialCount}) {
  const [state, dispatch] = useReducer(reducer, {count: initialCount});
  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'reset'})}>
        Reset
      </button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </div>
  );
}
class App extends React.Component{
    state = {
      aaa: 1
    }
    onClick(){
      this.setState(function(s){
        return {
          aaa: s.aaa +1
        }
      })
    }
    componentDidMount(){
      console.log("app mount")
    }
    componentDidUpdate(){
      console.log("app update")
    }
    render(){
      return <div><Counter initialCount={1}  />
              <h1 onClick={this.onClick.bind(this)}>{ this.state.aaa}</h1>
        </div>
    }
}
ReactDOM.render(<App />, container)
	
    </script>


</html>