React-router-dom 更改 URL 但不更新样式组件的主题提供程序的内容



你能帮我说出问题所在吗?我正在使用react-router-dom,当我尝试切换到某个页面时 - URL 正在更新,但不是内容。如果我刷新页面 - 内容正常

这是我的演示: https://github.com/azat-io/react-router-dom-demo/blob/master/App.js

这是代码:

import React from 'react'
import {
BrowserRouter as Router,
Route,
Switch,
Link,
} from 'react-router-dom'
import { Provider } from 'react-redux'
import { createStore, combineReducers } from 'redux'
import { render } from 'react-dom'
import styled, { ThemeProvider, createGlobalStyle } from 'styled-components'
import { normalize, selection } from 'polished'
import Home from 'containers/Home'
import Categories from 'containers/Categories'
import NotFound from 'containers/NotFound'
import theme from 'etc/theme'
const rootReducer = combineReducers({})
const store = createStore(rootReducer, window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__())
const GlobalStyle = createGlobalStyle`
${normalize()}
${({ theme }) => selection({
background: theme.primaryColor,
color: theme.primaryContrastColor,
})}
a {
display: block;
}
`
const Container = styled.div`
display: block;
min-height: 100%;
`
const App = () => (
<Provider store={store}>
<Router>
<ThemeProvider theme={theme}>
<Container>
<GlobalStyle />
<menu>
<Link to={'/'}>
{ 'to home' }
</Link>
<Link to={'/categories'}>
{ 'to categories' }
</Link>
</menu>
<Switch>
<Route exact path={'/'} component={Home} />
<Route path={'/categories'} component={Categories} />
<Route component={NotFound} />
</Switch>
</Container>
</ThemeProvider>
</Router>
</Provider>
)
render(<App />, document.getElementById('app'))

您的Container组件没有更新其子组件。所以问题来自样式组件。

一个可行的解决方案是将<Router>包裹在您的<Container>中,而不是相反......这样:

const App = () => (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Container>
<Router>
<React.Fragment>
<GlobalStyle />
<menu>
<Link to={"/"}>{"to home"}</Link>
<Link to={"/categories"}>{"to categories"}</Link>
</menu>
<Switch>
<Route exact path={"/"} component={Home} />
<Route path={"/categories"} component={Categories} />
<Route component={NotFound} />
</Switch>
</React.Fragment>
</Router>
</Container>
</ThemeProvider>
</Provider>
);

另一种解决方案(未经测试(是使用 styled('div'( 而不是 styled.div,并保持其余代码不变。

或者还有一件事(未经测试(是用<ContainerWrapper>替换<Container>,这是它的代码:const ContainerWrapper = props => <Container>{props.children}</Container>这样做的原因是有一个无状态函数,我们确信它会在路由更改时更新。

请随时让我知道哪个效果最好,以便调整此答案以供将来参考。

最新更新