redux实现todos

使用react-redux实现todos

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { Provider, connect } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
var nextTodoId = 4;
const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false,
      };
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state;
      }

      return {
        ...state,
        completed: !state.completed,
      };
    default:
      return state;
  }
};
// reducer
const todos = (
  state = [
    { text: 'a', id: 0, completed: true },
    { text: 'b', id: 1, completed: false },
    { text: 'c', id: 2, completed: false },
  ],
  action,
) => {
  switch (action.type) {
    case 'ADD_TODO':
      console.log([...state, todo(undefined, action)]);
      return [...state, todo(undefined, action)];
    case 'TOGGLE_TODO':
      return state.map(t => todo(t, action));
    default:
      return state;
  }
};
const visibilityFilter = (state = 'SHOW_ALL', action) => {
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
};
// 合并两个reducer
const todoApp = combineReducers({
  todos,
  visibilityFilter,
});

// store
const store = createStore(todoApp, applyMiddleware(thunkMiddleware));

// view
const Counter = ({ todos, dispatch, visibilityFilter }) => {
  let input1;
  handleAdd = () => {
    if (!input1.value.trim()) {
      return;
    }
    dispatch({
      type: 'ADD_TODO',
      id: nextTodoId++,
      text: input1.value,
    });
    input1.value = '';
  };
  return (
    <div>
      <input
        type="text"
        ref={node => {
          input1 = node;
        }}
      />
      <button onClick={handleAdd}>add</button>
      <ul>
        {todos.map(todo =>
          <li
            key={todo.id}
            {...todo}
            onClick={() => {dispatch({
                       type: 'TOGGLE_TODO',
                       id: todo.id
                     })} }
            style={{
                       fontSize: '30px',
      textDecoration: todo.completed ? 'line-through' : 'none',
        color: todo.completed ? 'red' : 'green'
    }}
            >
            {todo.text}
          </li>,
        )}
      </ul>
      <p>
        <span
          onClick={() => {
            dispatch({
              type: 'SET_VISIBILITY_FILTER',
              filter: 'SHOW_ALL',
            });
          }}
        >
          {visibilityFilter == 'SHOW_ALL'
            ? <span>显示所有 &nbsp;&nbsp;</span>
            : <a>显示所有 &nbsp;&nbsp;</a>}
        </span>

        <span
          onClick={() => {
            dispatch({
              type: 'SET_VISIBILITY_FILTER',
              filter: 'SHOW_ACTIVE',
            });
          }}
        >
          {visibilityFilter == 'SHOW_ACTIVE'
            ? <span>激活状态 &nbsp;&nbsp;</span>
            : <a>激活状态 &nbsp;&nbsp;</a>}
        </span>

        <span
          onClick={() => {
            dispatch({
              type: 'SET_VISIBILITY_FILTER',
              filter: 'SHOW_COMPLETED',
            });
          }}
        >
          {visibilityFilter == 'SHOW_COMPLETED'
            ? <span>完成状态 &nbsp;&nbsp;</span>
            : <a>完成状态 &nbsp;&nbsp;</a>}
        </span>
      </p>
    </div>
  );
};

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_ALL':
      return todos;
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed);
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed);
    default:
      throw new Error('Unknown filter: ' + filter);
  }
};

// container
const mapStateToProps = state => ({
  todos: getVisibleTodos(state.todos, state.visibilityFilter),
  visibilityFilter: state.visibilityFilter,
});
const CounterContainer = connect(mapStateToProps)(Counter);

// connect to store
const App = (
  <Provider store={store}>
    <CounterContainer />
  </Provider>
);

ReactDOM.render(App, mountNode);

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值