【问题标题】:Switch component doesn't update the view切换组件不更新视图
【发布时间】:2020-03-12 08:04:09
【问题描述】:

我使用 react-router-dom v5 遇到了我的 react 应用程序的问题。

当我手动更改路由或使用 时,组件不会更新,即使我正在刷新页面。

这是我的代码:

import React, { useEffect, useState } from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import openSocket from "socket.io-client"

import ChannelSelection from './auth/ChannelSelection'
import Home from './home/Home'

import AppContext from '@context/AppContext'

const App = () => {
  const [socket, setSocket] = useState()

  const [channel, setChannel] = useState('')
  const [pseudo, setPseudo] = useState('')

  const store = {
    user: {
      pseudo: pseudo,
      setPseudo: (pseudo) => setPseudo(pseudo)
    },
    app: {
      channel: channel,
      setChannel: (channel) => setChannel(channel)
    }
  }

  useEffect(() => {
    const host = '127.0.0.1'
    const port = '8080'

    setSocket(openSocket(host + ':' + port))
  }, [])

  return (
    <AppContext.Provider value={store}>
      <Router>
        <Switch>
          <Route exactPath="/" component={() => <ChannelSelection socket={socket} />} />
          <Route path="/:channel" component={() => <Home socket={socket} />} />
        </Switch>
      </Router>
    </AppContext.Provider>
  )
}

export default App

我现在有点困惑,因为我过去已经使用过 react-router-dom 并且从未遇到过这个问题。

提前谢谢你!

【问题讨论】:

  • 什么是exactPath 道具?错字,应该可以修复并关闭。

标签: reactjs websocket react-router


【解决方案1】:

我认为你应该使用 path 而不是 exactPath

<Route path="/" exact component={() => <ChannelSelection socket={socket} />}

如果您有多个名称相似的路径,该路径将很有用。像 path="/some"path="/some/path" 这就是你需要确切关键字的地方。

【讨论】:

    【解决方案2】:

    routes 中添加exact 属性并将exactPath 更改为path

    react-router-dom 中没有带有exactPath 名称的道具。

     <Route path="/" exact component={() => <ChannelSelection socket={socket} />} />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-29
      • 2016-03-20
      • 2020-05-06
      • 2020-01-24
      • 2019-05-12
      • 2019-01-19
      • 2017-07-21
      • 2019-11-09
      相关资源
      最近更新 更多