Extract Action Creator

  • addTodo
// action creator
const addTodo = (text, id) => {
  return {
    type: 'ADD_TODO',
    id: id
    text
  };
}

// AddTodo
let AddTodo = ({ dispatch }) => {
  let input,
      nextTodoId = 0
  return (
    <div>
      <input ref={node => {
        input = node
      }} />
      <button onClick={() => {
        dispatch(addTodo(input.value, nextTodoId++))
        input.value = ''
      }}>
        Add Todo
      </button>
    </div>
  )
}
  • setVisibilityFilte
// action creator
const setVisibilityFilter = (filter) => {
  return {
    type: 'SET_VISIBILITY_FILTER',
    filter
  }
}

// Change dispatch in mapDispatchToLinkProps
const mapDispatchToLinkProps = ( ... ) => {
  onClick: () => {
    dispatch(
      setVisibilityFilter(ownProps.filter)
    );
  }
}
  • toggleTodo
// action creator
const toggleTodo = (id) => {
  return {
    type: 'TOGGLE_TODO',
    id
  }
}

// Change dispatch in mapDispatchToTodoListProps
const mapDispatchToTodoListProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id));
    }
  }
}
Finally,我们完成了!demo完整代码

接下来,我们会接触一些更深入的概念,同样也会伴随一个例子帮助理解。


commit history in github

点击这个按钮可以查看各个版本

results matching ""

    No results matching ""