从v3迁移到v4 react-router时出错

时间:2017-05-06 08:19:56

标签: reactjs redux react-router react-router-redux react-router-dom

我决定使用react-router v4而不是v3并更改我的路径,以便它们与路由器和redux的v4一起使用,但我得到以下错误(我使用export default导出所有组件并且不忘记导出任何东西)。我的代码出了什么问题?

  

元素类型无效:需要一个字符串(用于内置组件)   或类/函数(对于复合组件)但得到:undefined。您   可能忘记从您定义的文件中导出组件。

我试图改变这个v3路由器代码,它起作用了:

<Router history={history}>
  <Route path="/" component={App}>
    <IndexRoute component={UserGrid}></IndexRoute>
    <Route path="/login" component={Login}></Route>
    <Route path="/users/:userId" component={UserPage}></Route>
    <Route path="/registration" component={RegistrationPage}></Route>
    <Route path="/topSecret" component={requireAuth(SecretComponent)}></Route>
  </Route>
</Router>

像这样进入v4代码:

const history = createBrowserHistory()

const router = (
  <Provider store={store}>
    <BrowserRouter history={history}>
        <App>
          <Route exact path="/" component={UserGrid}></Route>
          <Route path="/login" component={Login}></Route>
          <Route path="/users/:userId" component={UserPage}></Route>
          <Route path="/registration" component={RegistrationPage}></Route>
          <Route path="/topSecret" component={requireAuth(SecretComponent)}></Route>
        </App>
    </BrowserRouter>
  </Provider>
)

ReactDOM.render(
  router,
  document.getElementById('root')
)

App.js:

class App extends React.Component {
    render() {
        return (
            <div>
                <NavBar />
                {React.cloneElement(this.props.children, this.props)}
            </div>
        )
    }
}

function mapStateToProps (state) {
  return {
    session: state.session,
    users: state.users
  }
}

function mapDispatchToProps (dispatch) {
  return bindActionCreators(actionCreators, dispatch)
}


export default connect(mapStateToProps, mapDispatchToProps)(App)

商店:

import {applyMiddleware, createStore} from 'redux'
import {createLogger} from 'redux-logger'
import { connectRouter, routerMiddleware } from 'connected-react-router'
import thunk from 'redux-thunk'
import { createBrowserHistory } from 'history'
import rootReducer from '../reducers/rootReducer'
import async from '../middlewares/async'
import {authUser} from '../actions/actionCreators'

const history = createBrowserHistory()

const initialState = {
  bla-bla
}

const store = createStore(
  connectRouter(history)(rootReducer),
  initialState,
  applyMiddleware(
    async,
    thunk,
    routerMiddleware(history),
    createLogger()
  )
)

export default store

1 个答案:

答案 0 :(得分:1)

我删除了App中的{React.cloneElement(this.props.children, this.props)}(将道具传递给它的子容器)并将其替换为this.props.children并将需要状态的组件单独连接到商店,这解决了我的问题。但我仍然想知道为什么它不能与{React.cloneElement(this.props.children, this.props)}

一起使用