iT邦幫忙

2022 iThome 鐵人賽

DAY 15
0
Modern Web

React應用記錄誌系列 第 15

Day15實作練習 用Redux Toolkit做學習筆記列表

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20220930/20139800vTTbt9UDfy.png

1.configureStore

store.js

import {configureStore} from "@reduxjs/toolkit";
import notesReducer from '../notes/notesSlice';

export const store = configureStore({
    reducer: {
       notes:notesReducer
    }
})

2.Provider store

Index.js

import App from './App';
import {store} from './app/store';
import {Provider} from 'react-redux';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
     <App />
     </Provider>
  </React.StrictMode>
);

3.createSlice和reducers

notesSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = [    
		{ id: 1, title: ' Setp1 Install Redux Toolkit',content:'Lorem Ipsum is simply dummy text of the printing and typesetting industry. ' },
		{ id: 2, title: ' Setp2 Creating a Redux store',content:'Lorem Ipsum It is a long established fact. ' },
		{ id: 3, title: ' Setp3 Creating a Redux slice',content:'Lorem Ipsum There are many ' },
]

const notesSlice = createSlice({
    name:'notes',
    initialState,
    reducers:{
		noteAdd(state,action){
			state.push(action.payload)
		}
	}
})
export const selectAllNotes = (state) => state.notes;
export const {noteAdd}= notesSlice.actions
export default notesSlice.reducer

4.	建立組件NotesLis.js和NotesForm.js,加入useSelector(), useDispatch()

NotesLis.js
import { useSelector } from "react-redux";
import {selectAllNotes} from './notesSlice';
import React from 'react'

const NotesList = () => {
    const notes = useSelector(selectAllNotes)
    const allNotes = notes.map(note =>(
        <div className="article" key={note.id}>
            <h4>{note.title}</h4>
            <p>{note.content.substring(0,150)}</p>
        </div>
    ))

  return (
    <div  className="section">
      <div className="box">
         <h2>Learn Notes List</h2>
         <div>{allNotes}</div>
       </div>
    </div>
  )
}

export default NotesList

NotesForm.js

nanoid它是redux toolkit內建的一個隨機id產生器,所以 不需再從外部導入其他如uuid隨機id產生器模組。

import { useState } from "react";
import { useDispatch} from "react-redux";
import { nanoid } from "@reduxjs/toolkit";
import { noteAdd } from "./notesSlice";

const NotesForm = () => {
     const dispatch = useDispatch()
    const [title, setTitle] = useState('')
    const [content, setContent] = useState('')       

    const onTitleChanged = e => setTitle(e.target.value)
    const onContentChanged = e => setContent(e.target.value)

    const onSaveNoteClick =()=>{
        if (title && content){
            dispatch(
                noteAdd({
                    id:nanoid(),
                    title,
                    content
                }) 
            )

            setTitle('')
            setContent('')
        }
    }
       
    return (
        <div className="section">
            <h2>Add a New Note</h2>
            <form>
                <label htmlFor="postTitle">Title:</label>
                <input
                    type="text"
                    id="postTitle"
                    name="postTitle"
                    value={title}
                    onChange={onTitleChanged}
                />
                
                <label htmlFor="postContent">Content:</label>
                <textarea
                    id="postContent"
                    name="postContent"
                    value={content}
                    onChange={onContentChanged}
                />
                <button
                    type="button"
                    onClick={onSaveNoteClick}                    
                >Save Note</button>
            </form>
        </div>
    )
}
export default NotesForm


上一篇
Day14 Redux Toolkit介紹
下一篇
Day16 實作練習-2 音樂列表
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言