Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined` 类型错误:在`Router`中,属性`history`被标记为必需,但其值为`undefined`。
Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined` 类型错误:在`Router`中,属性`history`被标记为必需,但其值为`undefined`。
无法通过属性类型检查: 属性 history
在 Router
中被标记为必需,但其值为 undefined
。
Index.js
import {render} from 'react-dom'; import {Provider} from 'react-redux'; import { Router, browserHistory } from 'react-router'; import Sstore from './store/configureStore.js'; import routes from './routes'; import {loadMovies} from './actions/movieActions.js'; const store = Sstore; store.dispatch(loadMovies()); render(, document.getElementById('app') );
Route.js
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Home from './components/Home.js'; export default ();
在React Router v4中,你的配置应该像下面这样:
import { BrowserRouter, Route, Switch } from 'react-router-dom'; import { Provider } from 'react-redux'; import createStoreWithMiddleware from './createStoreWithMiddleware'; import reducers from './reducers';
自上一个版本以来,API已经发生了变化。还要注意的是,顺序很重要。将最具体的路径放在前面。
上述错误的原因是没有正确传递`history`属性给`Router`组件。而解决方法是确保在使用`BrowserRouter`组件时,正确地传递`history`属性。可以通过以下步骤解决这个问题:
1. 首先,在你的项目中安装`history`库。可以使用以下命令进行安装:
npm install history
2. 接下来,在你的代码中引入`createBrowserHistory`函数,并使用它创建一个`history`对象。可以在你的代码的顶部添加以下代码:
import { createBrowserHistory } from 'history'; const history = createBrowserHistory();
3. 最后,在使用`BrowserRouter`组件时,将`history`属性设置为刚刚创建的`history`对象。可以修改你的代码如下:
// 路由配置...
通过以上步骤,你应该能够解决这个错误,并正确地传递`history`属性给`Router`组件。
在我的项目中,我通过两个步骤解决了这种类型的错误:
- 首先,导入并声明
createBrowserHistory
,并创建一个自定义的history对象:import { BrowserRouter as StaticRouter, Router, Switch, Route, Link } from 'react-router-dom'; import createBrowserHistory from 'history/createBrowserHistory'; const customHistory = createBrowserHistory();
- 接下来,需要给Router组件添加history属性:
<Router history={customHistory}> <div> <Link to={'/.../' + linkName1}> {itemName1} </Link> <Link to={'/.../' + linkName2}> {itemName2} </Link> </div>
这是一个关于React Router的问题。错误提示是“Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined`”。
这个问题的原因是在使用react-router-redux v4示例时没有正确使用ConnectedRouter并传递history。可以在此链接中找到react-router-redux v4的正确示例:https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux#usage
为了解决这个问题,需要按照正确的示例配置项目。确保使用ConnectedRouter组件,并正确地将history传递给它。在这个示例中,作者在昨天配置了项目,并且一切都正常工作。
以下是一个可能的解决方法示例:
import { createBrowserHistory } from 'history'; import { ConnectedRouter } from 'react-router-redux'; const history = createBrowserHistory(); ReactDOM.render(, document.getElementById('root') );
在这个示例中,我们使用`createBrowserHistory`函数来创建一个history对象,并将其传递给ConnectedRouter组件的`history` prop中。
通过按照正确的示例配置项目,并正确地使用ConnectedRouter和传递history,就可以解决这个问题。