Redux存储值未在其他组件中更新

r3i60tvu  于 2023-04-12  发布在  其他
关注(0)|答案(2)|浏览(124)

我正在创建一个react应用程序,用于状态管理。当调用dispatch时,它工作正常,并更新组件中的值。但当我试图使用它时,其他组件中的值是一个空数组(可能是初始状态)。看起来存储值更新了,但它只在一个组件中可用(从中调用use dispatch)
这就是它工作的地方

import React from 'react';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { setNote, deleteNote } from './action';
import { useSelector } from 'react-redux';

export default function Account() {
  const dispatch = useDispatch();
  const notes = useSelector((state) => state.notes);
  console.log(notes);
  useEffect(() => {
    const token = localStorage.getItem('token');

    if (token) {
      fetch('http://localhost:3000/notes', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
      })
        .then((response) => response.json())
        .then((data) => {
          dispatch(setNote(data));
        })
        .catch((error) => console.error(error));
    }
  }, []);

  function redirect() {
    window.location.href = '/new';
  }
  function handleEditButton(id) {
    window.location.href = `/edit/${id}`;
  }

  function handleDelete(id) {
    const token = localStorage.getItem('token');
    fetch(`http://localhost:3000/notes/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    })
      .then((response) => response.text())
      .then((data) => {
        console.log(data);
        dispatch(deleteNote(id));
      })
      .catch((error) => console.error(error));
  }

  return (
    <div>
      <h1>Your Notes</h1>
      <button className="green" onClick={redirect}>
        Add New Note
      </button>
      {notes &&
        notes.map((note) => (
          <div className="note" key={note._id}>
            <h2>{note.title}</h2>
            <p>{note.content}</p>
            <p>Created: {note.dateCreated}</p>
            <p>Last Modified: {note.lastModified}</p>
            <button className="edit" onClick={() => handleEditButton(note._id)}>
              Edit Note
            </button>
            <button className="delete" onClick={() => handleDelete(note._id)}>
              Delete Note
            </button>
          </div>
        ))}
    </div>
  );
}

我的行动和减速器

export function addNote(notes) {
    return {
      type: 'ADD_NOTE',
      payload: notes
    }
  }
  
  export function updateNote(notes) {
    return {
      type: 'UPDATE_NOTE',
      payload: notes
    }
  }
  export function deleteNote(noteId) {
    return {
      type: 'DELETE_NOTE',
      payload: noteId
    }
  }
  

  export function setNote(notes) {
    return {
      type: 'SET_NOTE',
      payload: notes
    }
  }
const initialState = {
    notes: []
  }

export default function notesReducer(state = initialState, action) {
  
  switch (action.type) {
    case 'ADD_NOTE':
      return {
        ...state,
        notes: [...state.notes, action.payload]
      };
    case 'UPDATE_NOTE':
      return {
        ...state,
        notes: state.notes.map(note => note.id === action.payload.id ? action.payload : note)
      };
      case 'DELETE_NOTE':
        return {
          ...state,
          notes: state.notes.filter(note => note._id !== action.payload)
        };
      
      
  case 'SET_NOTE':
  return {
    ...state,
    notes: action.payload
  };

    default:
      return state
  }
}

我的应用程序组件。

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import notesReducer from './reducer.js'
import Account from './Account';
import Login from './Login';
import SignUp from './SignUp';
import Note from './Note';
import New from './New';
import Edit from './Edit';

const store = createStore(notesReducer);

function App() {
  return (
    <Provider store={store}>
    <Router>
      <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/" element={<SignUp />} />
        <Route path="/account" element={<Account />} />
        <Route path="/display" element={<Note />} />
        <Route path="/new" element={<New />} />
        <Route path="/edit/:id" element={<Edit/>} />

      </Routes>
    </Router>
    </Provider>
  )
}








export default App;

下面是我编辑组件,它是其中一个不能工作的组件。

import React, { useState } from "react";
    import { useSelector } from "react-redux";
    import { useParams } from "react-router-dom";

    export default function Edit() {
      const { id } = useParams();
      const note = useSelector(state => state.notes.find(note => note._id === id));
      const [title, setTitle] = useState(note.title);
      const [content, setContent] = useState(note.content);

      function handleEditNote() {
        const updatedNote = { id, title, content };
        // dispatch an action to update the note in the store and send a request to update the note on the server
      }

      return (
        <div>
          <div className="new">
            <h1>Edit Note</h1>
            <label>
              Title:
              <br />
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
            </label>
            <br />
            <label>
              Content:
              <br />
              <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
              />
            </label>
            <br />
            <button onClick={handleEditNote}>Save Changes</button>
          </div>
        </div>
      );
    }

即使我在编辑组件中控制台记录注解,没有Map它.它记录空数组.此外,帐户组件(它工作的地方),首先将其记录为空数组,它在获取和使用调度后填充.
我是新手,请帮帮忙。

hgb9j2n6

hgb9j2n61#

确保在需要访问note状态的组件中使用useSelector钩子
你可以添加console.log来尝试在redux操作中查找问题

h5qlskok

h5qlskok2#

试着从redux导入所有的笔记,当你让它们运行你的过滤器/查找功能。

const notes = useSelector((state) => state.notes);
const [note, setNote] = useState(null)

useEffect(() => {
  const note = notes.filter((note) => note._id == id);
  setNote(note);
}, [notes]);

相关问题