从redux中访问服务器道具?

时间:2016-04-06 13:45:46

标签: javascript reactjs redux react-engine

我尝试使用reduxreact-enginereact-router

我遇到的问题是,react-engine提供了来自服务器的props对象。如何从我的ProvidedApp

中访问这些道具

ProvidedApp.js

import React from 'react'
import { connect, Provider } from 'react-redux'
import App from './app'
import { mapStateToProps, mapDispatchToProps, store } from './redux-stuff'

// Connected Component
let ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

let ProvidedApp = () => (
  <Provider store={store}>
    <ConnectedApp/>
  </Provider>
)

export default ProvidedApp

Routes.js

import React from 'react'
import { Router, Route } from 'react-router'

import Layout from './views/Layout'
import App from './views/ProvidedApp'

module.exports = (
  <Router>
    <Route path='/' component={Layout}>
      <Route path='/app' component={App} />
      <Route path='/app/dev' component={App} />
    </Route>
  </Router>
)

我也认为我的配置有点不稳定,我无法让Provider以任何其他方式工作。如果有一种方法可以让Provider包裹Router我喜欢让它发挥作用。

这里有一些代码,当我将Provider移到Router以上时,它会是什么样子

ConnectedApp.js

import React from 'react'
import { connect, Provider } from 'react-redux'
import App from './app'
import { mapStateToProps, mapDispatchToProps} from './redux-stuff'

let ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

export default ConnectedApp

Routes.js

import React from 'react'
import { Provider } from 'react-redux'
import { Router, Route } from 'react-router'
import { store } from './redux-stuff'

import Layout from './views/Layout'
import App from './views/ConnectedApp'

module.exports = (
  <Provider store={store}>
    <Router>
      <Route path='/' component={Layout}>
        <Route path='/app' component={App} />
      </Route>
    </Router>
  </Provider>
)

我收到此错误:

Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(App)".

更新

我发现我可以在ProvidedApp中的第一个示例中访问他的代码。但我不知道我应该如何将它传递给Redux。

let ProvidedApp = (props) => {
  console.log(props)
  return (
    <Provider store={store}>
      <ConnectedApp/>
    </Provider>
  )
}

1 个答案:

答案 0 :(得分:0)

好像我需要打包reducerstore并将ServerProps传递到默认状态。

let getDefaultState = (serverProps) => {
  return {
    'appName': serverProps.appName 
  }
}

let getReducer = (serverProps) => {
  let defaultState = getDefaultState(serverProps)
  return (state = defaultState, action) => {

  }
}

let getStore = (serverProps) => {
  let reducer = getReducer(serverProps)
  return store = createStore(reducer)
}

let ConnectedApp = connect(
  mapStateToProps,
  mapDispatchToProps
)(App)

let ProvidedApp = (serverProps) => {
  return (
    <Provider store={getStore(serverProps)}>
      <ConnectedApp/>
    </Provider>
  )
}

这太丑了:/