【问题标题】:Redux-react connect function does not work for root componentRedux-react 连接功能不适用于根组件
【发布时间】:2017-10-14 18:19:36
【问题描述】:

我正在使用中间件从 indexeddb 恢复 Redux 存储。我想在根组件中使用该数据进行路由,以检查用户是否已连接。但是好像connect函数并没有把根组件state连接到Redux。

当我调试时,我看到mapStateToProps 从未真正运行过。这是 index.js 的相关部分:

class AppProvider extends Component {
  constructor (props) {
    super(props)
    this.state = {}
  }

  componentWillMount () {
    persistStore(store, {storage: localforage}) // Populates the store from indexedDB
  }

  render () {
    return (
      <Provider store={store}>
        <Router history={history}> // Here I need the user from redux
          <Route path="/login" render={() => (
          this.state.user ? ( <Redirect to="/dashboard"/> ) : ( <LoginPage/> )
        )}/>
        </Router>
      </Provider>
    )
  }
}

function mapStateToProps (state, ownProps) {
  return {
    user: state.user // function never runs!
  }
}

withRouter(connect(mapStateToProps, {})(AppProvider))

render(
  <AppProvider/>,
  document.getElementById('root')
)

更新: 尝试此操作时:

const Root = withRouter(connect(mapStateToProps, {})(AppProvider))

render(
  <Root/>,
  document.getElementById('root')
)

我明白了

未捕获的类型错误:无法读取未定义的属性“路由”

【问题讨论】:

  • 尝试从 'react-router-dom' 而不是 'react-router' 导入

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


【解决方案1】:

您没有使用连接的组件。

withRouterconnect 都不会修改原始组件。它们只是返回一个新组件。

试试这个;

const AppProviderWithRedux = withRouter(connect(mapStateToProps, {})(AppProvider))

render(
  <AppProviderWithRedux/>,
  document.getElementById('root')
)

【讨论】:

  • 由于某种原因它破坏了路由并给了我Uncaught TypeError: Cannot read property 'route' of undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2019-11-01
  • 2018-05-14
  • 2019-09-05
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多