See the Pen (Example)Redux-ToDoList-v1 by Shark (@sharkdeng) on CodePen.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src='https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.min.js'></script>
</head>
<body>
<input id="todo" type="text">
<button id="submit">submit</button>
<div id="container"></div>
<script>
const reducer = Redux.combineReducers({
todos: (state = [], action) => {
const newState = Object.assign([], state);
if (action.type == 'add') {
newState.push(action.item);
}
if (action.type == 'remove') {
newState.splice(action.index, 1);
}
return newState;
}
});
const store = Redux.createStore(reducer);
// update UI
const render = () => {
// make sure it is empty
const container = document.getElementById('container');
container.innerHTML = '';
const state = store.getState();
// iterate each item
state.todos.forEach((todo, i) => {
// create an item
const e = document.createElement('div');
e.innerHTML = todo;
container.appendChild(e);
e.onclick = () => {
store.dispatch({
type: 'remove',
index: i
});
render();
}
});
};
document.getElementById('submit').onclick = () => {
store.dispatch({
type: 'add',
item: document.getElementById('todo').value
});
render();
};
</script>
</body>
</html>