gpt4 book ai didi

javascript - 带有反应钩子(Hook)的 react 路由器 DOM 不起作用

转载 作者:行者123 更新时间:2023-12-03 14:16:21 25 4
gpt4 key购买 nike

我的 app.js 组件

import React, { lazy, Suspense } from 'react'
import './App.css'
// import io from 'socket.io-client'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'

//lazy load the components
const Login = lazy(() => import('./Components/Login/Login'))
const Home = lazy(() => import('./Components/Home/Home'))
const List = lazy(() => import('./Components/List/List'))
const Page404 = lazy(() => import('./Components/404/'))

function App() {
return (
<Router>
<div className='App'>
<Suspense
fallback={
<div
style={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: '100vh',
fontFamily: "'Ubuntu', sans-serif",
fontSize: '30px'
}}
>
Loading..
</div>
}
>
<Switch>
<Route exact path='/'>
<Home />
</Route>
<Route path='/create_user_name'>
<Login />
</Route>
<Route path='/list'>
<List />
</Route>
<Route component={Page404} />
</Switch>
</Suspense>
</div>
</Router>
)
}

export default App

当我尝试使用 history.push('/list') 时,我的页面 URL 正在更改,但页面内容没有更改。

示例:当我转到 /create_user_name 并单击按钮 history.push('/list') 时,就会执行。页面的 URL 从 /create_user_name 更改为 /list,但页面内容保持不变。它仍然包含为 /create_user_name 路由制作的相同 UI,而不是 /list UI。

history.js 组件

import { createBrowserHistory } from 'history'
const history = createBrowserHistory()

export default history

我正在使用 reducer 。存储组件

import io from 'socket.io-client'
import history from '../Components/history'
// import axios from 'axios'
//connect to the server
const socket = io.connect('localhost:3030')
console.log(socket)

//listen for number of users
export const users = socket.on('users', users => {
console.log(users)
return users
})

export const setUser = (state, action) => {
switch (action.type) {
case 'SET_NAME':
console.log(action.name)
const data = {
name: action.name
}

//sent user using socket
socket.emit('Create_name', data)
console.log(history)
history.push('/list') // I CALL THE HISTORY.PUSH HERE

return state

default:
console.log('Default State')
break
}
}

很抱歉,如果之前有人问过这个问题。

最佳答案

1.将历史记录传递给路由器:

import { Router } from 'react-router-dom'
import history from './history'
...
function App() {
return (
<Router history={history}>
...
</Router>
)
}

确保导入Router而不是BrowserRouter

As BrowserRouter uses its own history and does not accept any outer history property, we have to use Router instead of it.

2.现在,每当你想在 React 组件之外使用历史记录时,你首先导入它,然后使用它。

import history from './history'
...
history.push('/list');

这样路由器就能知道对历史记录所做的更改。

当你在 React 组件内部时,你可以直接使用 useHistory钩子(Hook)

关于javascript - 带有反应钩子(Hook)的 react 路由器 DOM 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60041085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com