Redux-Toolkit2
Redux-Toolkit2
Index.js
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// store.js
import { configureStore } from '@reduxjs/toolkit';
import todoReducer from './todoSlice';
// todoSlice.js
import { createSlice } from '@reduxjs/toolkit';
name: 'todos',
initialState,
reducers: {
// App.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from './todoSlice';
import TodoList from './TodoList';
setText('');
}
};
return (
<div>
<input
type="text"
value={text}
onChange={e => setText(e.target.value)}
placeholder="Enter a new todo"
/>
<button onClick={handleAddTodo}>Add</button>
<TodoList />
</div>
);
};
// TodoList.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { deleteTodo } from './todoSlice';
import TodoItem from './TodoItem';
return (
<div>
{todos.map(todo => (
<div key={todo.id}>
<TodoItem todo={todo} />
<button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
</div>
))}
</div>
);
};
// TodoItem.js
import React from 'react';
So, even though the addTodo reducer function expects state and
action, the dispatch function is responsible for passing the action
object (containing the payload) to the reducer function when it's
dispatched.