You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Store值在其他组件中不更新的问题求助

React Redux状态更新后其他组件无法获取最新值的解决方案

问题核心

你遇到的问题根源是使用window.location.href跳转页面会触发整个应用刷新,导致Redux Store被重新初始化,之前通过dispatch更新的状态全部丢失,所以Edit组件只能拿到初始的空数组。

解决方案

1. 替换页面跳转方式

使用react-router-dom提供的useNavigate钩子进行页面跳转,这是单页应用的正确导航方式,不会刷新整个应用,Redux状态会被保留。

修改Account组件:

import React from 'react';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { setNote, deleteNote } from './action';
import { useNavigate } from 'react-router-dom'; // 导入useNavigate

export default function Account() {
  const dispatch = useDispatch();
  const notes = useSelector((state) => state.notes);
  const navigate = useNavigate(); // 初始化导航钩子

  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() {
    navigate('/new');
  }
  function handleEditButton(id) {
    navigate(`/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>
  );
}

2. 修复Edit组件的潜在问题

Edit组件初始化时可能note还未加载(比如Redux状态还没更新),直接访问note.title会报错,需要添加监听和加载状态:

import React, { useState, useEffect } 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('');
  const [content, setContent] = useState('');

  // 监听note变化,同步更新本地状态
  useEffect(() => {
    if (note) {
      setTitle(note.title);
      setContent(note.content);
    }
  }, [note]);

  function handleEditNote() {
    const updatedNote = { id, title, content };
    // 后续添加dispatch更新状态和请求后端的逻辑
  }

  // 未加载到note时显示加载状态
  if (!note) {
    return <div>Loading...</div>;
  }

  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>
  );
}

额外注意事项

  • 所有页面跳转都必须使用react-router的导航方法(useNavigate或Navigate组件),禁止用window.location.href或window.location.replace,避免刷新丢失状态。
  • 如果需要状态持久化(比如页面刷新后仍保留),可以使用redux-persist库,将Redux状态存储到localStorage或sessionStorage中。

内容的提问来源于stack exchange,提问作者The dumb coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:42:54