如何使用 React Context API 跨多个 Routes 拥有状态?

Posted

技术标签:

【中文标题】如何使用 React Context API 跨多个 Routes 拥有状态?【英文标题】:How to use React Context API to have a state across multiple Routes? 【发布时间】:2021-03-04 22:22:41 【问题描述】:

我正在尝试了解上下文 API 的工作原理。我想保留一个可以从任何类组件更新的全局状态。目前,当我尝试使用提供的函数更新我的 Context 时,它只会在本地更新值。在我的代码中,我尝试将字段“Day”更新为“Hello”,并且只有在呈现 Writer 时才能看到更改。一旦我要求我的浏览器呈现“Reader”,该值又是“Day”。为什么会这样?这是我的代码,我尽可能地简化了它:

index.js:
    import React from "react";
    import ReactDOM from "react-dom";
    import ThemeContextProvider from "./ThemeContext";
    
    import App from "./App";
    
    ReactDOM.render(
    <ThemeContextProvider>
       <App />
    </ThemeContextProvider>,
  document.getElementById("root")
);
app.js:
import React from "react";
import Writer from "./Writer.js";
import Reader from "./Reader.js";
import  Context  from "./ThemeContext.js";
import BrowserRouter as Router, Switch, Route from 'react-router-dom';

class App extends React.Component 
  static contextType = Context;
  constructor(props) 
    super(props);
  
  render() 
    return (
      <div className="app">
        <Router>
          <Switch>
            <Route path="/writer" component=Writer></Route>
            <Route path="/reader" component=Reader></Route>      
          </Switch>
        </Router>
      </div>
    );
  


export default App;
context.js:
import React,  Component  from "react";
const Context = React.createContext();
const  Provider, Consumer  = Context

// Note: You could also use hooks to provide state and convert this into a functional component.
class ThemeContextProvider extends Component 
  state = 
    theme: "Day"
  ;

  setTheme = (newTheme) => 
    this.setState(theme: newTheme)
  ;

  render() 
    return <Provider value=theme: this.state.theme, setTheme: this.setTheme>this.props.children</Provider>;
  


export  ThemeContextProvider, Consumer as ThemeContextConsumer, Context ;
writer.js:
import React from "react";
import Context from "./ThemeContext";

class Writer extends React.Component 
  static contextType = Context
  constructor(props) 
    super(props);
    this.write = this.write.bind(this)
  

  write () 
    this.context.setTheme("hello")
  

  render() 
    return (
      <div>
        <button onClick=this.write>press</button>
        <p>this.context.theme</p> 
      </div>
    );
  


export default Writer;
reader.js:
import React from "react";
import  Context, ThemeContextConsumer  from "./ThemeContext";

class Reader extends React.Component 
  static contextType = Context;
  constructor(props) 
    super(props);
  
  render () 
    return(
          <div>
            <p>this.context.theme</p>
          </div>
  );


export default Reader;

【问题讨论】:

【参考方案1】:

你如何处理不同页面的操作?如果现在,您可以通过直接在搜索顶部浏览器输入占位符中键入来手动处理它。然后它不会工作,因为页面得到refresh。仅使用 context api 不会使您的数据持久化。您需要结合使用某种storage 以使其持久

无论如何,如果没有页面refresh 发生,您的代码应该可以工作。要在不同的页面中查看它,您可以使用 Link(来自 react-router-dom 包)或基本上是 button 将您重定向到不同的页面,如下所示:-

只需将其添加到您的 Writer.js component 以进行测试:-
import React from "react";
import  Link  from 'react-router-dom'
import Context from "./ThemeContext";

class Writer extends React.Component 
  static contextType = Context
  constructor(props) 
    super(props);
    this.write = this.write.bind(this)
  

  write () 
    this.context.setTheme("hello")
  

  render() 
    return (
      <div>
        <button onClick=this.write>press</button>
        <p>this.context.theme</p> 
        <Link to="/reader">Go to Reader page</Link>
      </div>
    );
  


export default Writer;

【讨论】:

以上是关于如何使用 React Context API 跨多个 Routes 拥有状态?的主要内容,如果未能解决你的问题,请参考以下文章

React context API-我如何从 useEffect 钩子中分派一个动作?

在组件之间路由时如何保持 React 新的 Context API 状态?

如何获取数据并存储在 React Context API 中?

在 React.js 的父组件中使用 react-router 时,如何使用 react context API 将数据从父组件传递到子组件?

使用 Context API 示例解释 React 高阶组件

使用Context API示例解释的React高阶组件