Index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
Store.js
import {createStore} from 'redux'
import rootReducer from './reducer/index'
const store = createStore(rootReducer);
export default store;
reducer/index.js
combineReducers=>將多個reducer合併
import todoReducer from "./todoReducer";
import { combineReducers } from "redux";
const rootReducer = combineReducers({
todoReducer
})
export default rootReducer;
todoReducer.js
const initialData = {
list:[]
}
const todoReducer = (state = initialData, action) => {
switch(action.type){
case "ADDTODO":
const { id,data} = action.payload;
return{
...state, list:[
...state.list,
{
id:id,
data:data
}
]
}
case "CLEARTODO":
return{
...state,
list:[]
}
default:return state;
}
}
export default todoReducer;
Action.js
import {v4 as uuidv4} from "uuid";
export const addTodo =(data)=>{
return{
type:"ADDTODO",
payload:{
id: uuidv4(),
data:data
}
}
}
export const cleardTodo =(data)=>{
return{
type:"CLEARTODO",
}
Todo.js
import React ,{ useState }from 'react'
import { useSelector,useDispatch } from 'react-redux';
import {addTodo,cleardTodo } from '../action/index';
const Todo = () => {
const [input,setInput] = useState("");
const list = useSelector((state)=>state.todoReducer.list)
const dispatch = useDispatch();
return (
<div className="container">
<div className="app-box">
<div className="header">Add Todoitem Here</div>
<input
className="line-input"
type="text"
placeholder='Add TodoItems...'
value={input}
onChange={(e)=>setInput(e.target.value)} />
<i
className='fa fa-plus add-btn'
onClick={()=>dispatch(addTodo(input),
setInput(''))}></i>
<div >
{ list.map((e)=>{
return(
<div className='list-item'key={e.id}>
<h3>{e.data}</h3>
</div>
)
})
}
</div>
<div>
<button
className='button-delete'
onClick={()=>dispatch(cleardTodo())}>Clear All</button>
</div>
</div>
</div>
)
}
export default Todo