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

React Router v4组件状态不保留问题求解决方案(附计数器示例)

解决React Router v4不保留组件历史状态的问题

嘿,我来帮你搞定这个状态保留的问题!你遇到的核心问题是直接修改this.props.location.state的方式不对——React里props是只读的,而且这种操作也不符合React Router的状态传递逻辑,所以自然没法保留住状态。

问题分析

你原来的代码里直接给this.props.location.state赋值,这其实不会被React Router识别和保存。因为location对象是React Router管理的不可变对象,修改它不会触发任何路由状态的更新,当你切换路由再回来时,之前的状态自然就丢失了。

解决方案1:通过history传递路由状态

正确的做法是用history.push或history.replace方法来携带状态,同时确保组件能拿到history props(可以用withRouter高阶组件包裹组件)。

修改后的完整代码:

import React, { Component } from "react";
import { withRouter } from "react-router-dom";

class Schedule extends Component {
  constructor(props) {
    super(props);
    // 初始化时优先读取路由携带的state,没有则从0开始
    this.state = { 
      counter: props.location.state?.counter || 0 
    };
    this.holdState = this.holdState.bind(this);
  }

  holdState() {
    const newCounter = this.state.counter + 1;
    this.setState({ counter: newCounter });
    
    // 用replace更新当前路由的状态(如果是跳转到其他路由就用push)
    this.props.history.replace({
      pathname: this.props.location.pathname,
      state: { counter: newCounter }
    });
  }

  render() {
    return (
      <div>
        <p>当前计数: {this.state.counter}</p>
        <button onClick={this.holdState}>增加计数</button>
        {/* 可以添加路由链接测试,比如跳转到其他页面再返回 */}
      </div>
    );
  }
}

// 用withRouter包裹,让组件获取到history、location等路由props
export default withRouter(Schedule);

解决方案2:用localStorage持久化状态

如果你的需求是即使刷新页面、关闭浏览器后再打开,状态依然保留,那可以用浏览器的localStorage来持久化数据:

import React, { Component } from "react";

class Schedule extends Component {
  constructor(props) {
    super(props);
    // 从localStorage读取之前保存的计数,没有则默认0
    this.state = { 
      counter: parseInt(localStorage.getItem('scheduleCounter')) || 0 
    };
    this.holdState = this.holdState.bind(this);
  }

  holdState() {
    const newCounter = this.state.counter + 1;
    this.setState({ counter: newCounter });
    // 将新计数保存到localStorage
    localStorage.setItem('scheduleCounter', newCounter.toString());
  }

  render() {
    return (
      <div>
        <p>当前计数: {this.state.counter}</p>
        <button onClick={this.holdState}>增加计数</button>
      </div>
    );
  }
}

export default Schedule;

关键提示

  • 永远不要直接修改this.props里的内容,React的设计理念是props只读,所有状态更新都要通过正确的API来完成。
  • 如果是路由间的状态传递,一定要用history.push/replace的state参数来携带数据,这样切换路由时状态会被React Router保留。

内容的提问来源于stack exchange,提问作者wawrzon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:17:21