如何将React-Router-Dom与上下文API V6一起使用?

发布于 2025-02-09 07:38:52 字数 2510 浏览 0 评论 0原文

我在pc组件中更改value,但没有反映在br1组件中。如果我不使用React-Router-dom,一切都很好,但是我需要路线。

app.js代码

import React, { createContext, useState } from 'react';
import './App.css';
import {  BrowserRouter as Router,   Routes,  Route } from "react-router-dom";
import BR1 from './Components/BR1';
import PC from './Components/P_c1'
import BR from './Components/BR';

export const BRcontext = createContext();

function App() {
  const [value, setValue] = useState(false)
  return (
    <div>
    <BRcontext.Provider value={{value, setValue}}>
      <Router>
        <Routes>
          <Route path='/PC' element={<PC/>} />
          <Route path='/BR1' element={<BR1/>} />
          <Route path='/BR' element={<BR/>} />
        </Routes>
      </Router>
    </BRcontext.Provider>
    </div>
  );
}

export default App;

PC代码

import React, { useContext } from 'react'
import './Profile.css';
import { BRcontext } from '../App';

export default function Profile() {

    const {value, setValue} = useContext(BRcontext);

    return (
        <div>
            <div className='container mt-5'>
                <div className='row'>
                    
                    <div>
                       
                        <h3 className='mt-5'>Send Request</h3>
                        <button className='btn btn-success mt-3 ps-3 pe-3' onClick={()=>{setValue(true)}}>Request</button>
                       
                       
                    </div>
                </div>
            </div>
        </div>
    )
}

BR1代码

import React, { useContext } from 'react'
import BR from './BR'
import { BRcontext } from '../App'
import { Link } from 'react-router-dom';

export default function BR1() {
    const {value} = useContext(BRcontext);
    // let navigate = useNavigate();
  return (
    <div>
        {console.log(value)} //this remains false
      {value ? <Link to="/BR"/>: console.log('hello there!')}
    </div>
  )
}

在BR1代码中,我希望valuepc单击组件中的一个按钮中单击

链接 - https://codesandbox.io/s/great-star-star-star-bzhuvw?file=/ src/app.js

I am changing the value in PC component but it is not reflected in the BR1 component. If I don't use react-router-dom, everything works fine, but I need the routes.

App.js code

import React, { createContext, useState } from 'react';
import './App.css';
import {  BrowserRouter as Router,   Routes,  Route } from "react-router-dom";
import BR1 from './Components/BR1';
import PC from './Components/P_c1'
import BR from './Components/BR';

export const BRcontext = createContext();

function App() {
  const [value, setValue] = useState(false)
  return (
    <div>
    <BRcontext.Provider value={{value, setValue}}>
      <Router>
        <Routes>
          <Route path='/PC' element={<PC/>} />
          <Route path='/BR1' element={<BR1/>} />
          <Route path='/BR' element={<BR/>} />
        </Routes>
      </Router>
    </BRcontext.Provider>
    </div>
  );
}

export default App;

PC code

import React, { useContext } from 'react'
import './Profile.css';
import { BRcontext } from '../App';

export default function Profile() {

    const {value, setValue} = useContext(BRcontext);

    return (
        <div>
            <div className='container mt-5'>
                <div className='row'>
                    
                    <div>
                       
                        <h3 className='mt-5'>Send Request</h3>
                        <button className='btn btn-success mt-3 ps-3 pe-3' onClick={()=>{setValue(true)}}>Request</button>
                       
                       
                    </div>
                </div>
            </div>
        </div>
    )
}

BR1 code

import React, { useContext } from 'react'
import BR from './BR'
import { BRcontext } from '../App'
import { Link } from 'react-router-dom';

export default function BR1() {
    const {value} = useContext(BRcontext);
    // let navigate = useNavigate();
  return (
    <div>
        {console.log(value)} //this remains false
      {value ? <Link to="/BR"/>: console.log('hello there!')}
    </div>
  )
}

In BR1 code, I want the value to become true when a button in the PC component is clicked

Link - https://codesandbox.io/s/great-star-bzhuvw?file=/src/App.js

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你对谁都笑 2025-02-16 07:38:52

除非直接更改浏览器URL,否则似乎无法从 /PC到 /BR1导航,并且这样做,您会因为它在内存中而失去当前的上下文值。如果您打算保持这种行为,则应考虑每次更改上下文值并使用先前的持久性持久性进行初始化。

使用浏览器的本地存储的一个示例:

// Helper function to read the storaged value if it exists
function getPersistedValue() {
  const serializedValue = localStorage.getItem('value')

  try {
    if (!serializedValue) {
      throw new Error('No previously persisted value found')
    }

    return JSON.parse(serializedValue)
  } catch {
    return false
  }
}

// Using the helper function to initialize the state
const [value, setValue] = useState(getPersistedValue())

// Synchronizing the persisted value on local storage with the in-memory one
useEffect(() => {
  localStorage.setItem('value', JSON.stringify(value))
}, [value])

如果需要,我将您的代码沙盒分叉并应用了这些更改: https://codesandbox.io/s/router-context-forked-uqhzye

It seems there's no way to navigate from /PC to /BR1 unless changing the browser URL directly, and by doing this, you lose the current context value because it's in memory. If you intend to keep this behaviour, you should consider persisting the context value every time you change it and initialize it with the previously persisted one.

An example using the browser's local storage:

// Helper function to read the storaged value if it exists
function getPersistedValue() {
  const serializedValue = localStorage.getItem('value')

  try {
    if (!serializedValue) {
      throw new Error('No previously persisted value found')
    }

    return JSON.parse(serializedValue)
  } catch {
    return false
  }
}

// Using the helper function to initialize the state
const [value, setValue] = useState(getPersistedValue())

// Synchronizing the persisted value on local storage with the in-memory one
useEffect(() => {
  localStorage.setItem('value', JSON.stringify(value))
}, [value])

If you want, I forked your Code Sandbox and applied these changes: https://codesandbox.io/s/router-context-forked-uqhzye.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文