我正在尝试做一个有历史的基本路由器,我有:
import {BrowserRouter, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory'
...
render() {
return (
<BrowserRouter>
<Switch>
<Route path="/login" component={PageA}/>
<Route path="/dashboard" component={PageB}/>
<Route path="/companies" component={PageC}/>
</Switch>
</BrowserRouter>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))但我一直在想:
Uncaught Error: React.Children.only expected to receive a single React element child此错误在控制台中重复四次。
我在论坛上跟踪了许多其他的答案,但它仍然不起作用。
这是怎么回事?
发布于 2019-02-04 20:40:53
保持事物清洁:
您应该在src中创建一个history.js,如下所示:
import createHistory from 'history/createBrowserHistory';
export default createHistory();在您的index.js中,导入Router而不是BrowserRouter,并将历史作为一个支柱传递,如下所示:
import {Router, Route, Switch} from 'react-router-dom';
import history from '../history' // relative path to the file you created above...
...
render() {
return (
<Router history={history}> // pass it as a prop here...
<Switch>
<Route path="/login" component={PageA}/>
<Route path="/dashboard" component={PageB}/>
<Route path="/companies" component={PageC}/>
</Switch>
</Router>
)
}
}现在您可以使用history.push('/path_you_want')在动作之后重定向等等..。
备注:如果你不使用redux,这可能是过火了.为了更简单地重定向,请查看库提供的<Redirect />组件..。提供示例的更多信息:https://reacttraining.com/react-router/web/api/Redirect
https://stackoverflow.com/questions/54523647
复制相似问题