Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

fix: reducer only exec once when reducer set inner function component #1027

Merged
merged 1 commit into from
Apr 8, 2019

Conversation

yuanyan
Copy link
Collaborator

@yuanyan yuanyan commented Apr 8, 2019

Current will exec twice when reducer direct set inner function component, this pr fix it:

function init(initialCount) {
  return {count: initialCount};
}

function App({initialCount}) {
  const [state, dispatch] = useReducer(function reducer(state, action) {
   // Only exec once when dispatch new state
    console.log(action, state);
    switch (action.type) {
      case 'increment':
        return {count: state.count + 1};
      case 'decrement':
        return {count: state.count - 1};
      case 'reset':
        return init(action.payload);
      default:
        throw new Error();
    }
  }, initialCount, init);
  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({type: 'reset', payload: initialCount})}>

        Reset
      </button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </>
  );
}

@yuanyan yuanyan requested a review from yongningfu April 8, 2019 04:14
@yuanyan yuanyan merged commit 8f941b1 into master Apr 8, 2019
@delete-merged-branch delete-merged-branch bot deleted the fix-useReducer branch April 8, 2019 15:18
@yuanyan yuanyan mentioned this pull request Apr 9, 2019
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants