通过上下文传递商店,<Provider>无法在基于connect()的方案中工作

Gre*_*ade 4 javascript reactjs redux react-redux

编辑:总结 - 我的问题的最初原因实际上是一个错字:由于资本'G'它没有工作.

然而,善意的回答者不仅解决了错字,而且解决了我采取的方法中的错误前提 - 如果您也使用提供商使用连接传递商店,他们的答案与您相关.我已更新问题的标题以反映这一点.


我试图按照令人敬畏的redux视频中的说明进行操作,但是使用<Provider>react-redux 传递给商店时感到很悲伤.

我有一个根组件:

export default class Root extends Component {
   render() {

      const { store } = this.props

      return (
         <Provider store={store}>
            <div>
               <ReduxRouter />
               <DevTools />
            </div>
         </Provider>
      )
   }
}
Run Code Online (Sandbox Code Playgroud)

一个试图使用商店的演示组件:

const ProjectsSummary = (props, {store}) => {
   const state = store.GetState();
   const { projects } = state;

   return (
      <div className="home-projects col-md-10">
          <h3>Projects</h3>
          <ul>
              { projects.map(p => <li key={p.id}>{p.contract.client}</li>) }
          </ul>
      </div>
   )
}

ProjectsSummary.contextTypes = {
   store: React.PropTypes.object
};

class Home extends BasePage {

   render() {
      return (
         <div className="home-page container-fluid">
             {super.render()}
             <HomeLeftBar/>
             <HomePageHeader/>
             <ProjectsSummary/>
         </div>
      )
   }
    }

export default connect()(Home)
Run Code Online (Sandbox Code Playgroud)

我得到"Uncaught TypeError:store.GetState不是函数"

这家商店来自这里:

import configureStore from './store/configureStore'

const store = configureStore({
   security:{
      jwt: 'mock'  // Mock data supplied below: only loaded when this is set.
   }, 
   projects: [
      {
            // elided for brevity
      }
   ]
})

/**
 * Main application render method that attaches it
 * to the HTML page.
 */
render(
   <Root store={store}/>,
   document.getElementById('app')
)
Run Code Online (Sandbox Code Playgroud)

并在此处创建:

export default (initialState) => {
   const store = createDevStore(initialState)

   if (module.hot) {
      // Enable Webpack hot module replacement for reducers
      module.hot.accept(['../../common/reducers', '../reducers'], () => {
         const nextRootReducer = require('../../common/reducers')
         const nextBrowserReducers = require('../reducers')
         store.replaceReducer(nextRootReducer(nextBrowserReducers))
      })
   }

   return store
}

function createDevStore(initialState){
   if(initialState && initialState.security && initialState.security.jwt === 'mock')
      return mockCreateStore(rootReducer(browserReducers), initialState)
   else
      return finalCreateStore(rootReducer(browserReducers))
}

const mockCreateStore = compose(
   reduxReactRouter({routes, createHistory}),
   applyMiddleware(createLogger()),
   DevTools.instrument()
    )(createStore)
Run Code Online (Sandbox Code Playgroud)

(不是我的代码,支持反应本机和浏览器客户端的框架,我正在开始工作)

我错过了什么?


我正在从视频中复制它 - 注意AddTodo组件没有使用connect()"包装":

const AddTodo = (props, { store }) => {
  let input;

  return (
    <div>
      <input ref={node => {
        input = node;
      }} />
      <button onClick={() => {
        store.dispatch({
          type: 'ADD_TODO',
          id: nextTodoId++,
          text: input.value
        })
        input.value = '';
      }}>
        Add Todo
      </button>
    </div>
  );
};
AddTodo.contextTypes = {
  store: React.PropTypes.object
};
Run Code Online (Sandbox Code Playgroud)

Dan*_*mov 14

这个答案是正确的,但我想澄清一些事情.

你似乎对表现和容器组件以及connect()那里的角色有很多困惑.我建议您再次观看相关视频,并确保在最后观看它们.

  1. 实际上,store.GetState()这不是一种有效的方法; store.getState()是.
  2. 如果您store.getState()手动使用,您还必须使用store.subscribe()某处,以便始终获得最新状态.AddTodo您从视频中粘贴的示例组件本身不起作用 - 它只在视频中起作用,因为我们store.subscribe(render)在最顶端有一个.
  3. 课程后面的视频讨论了如何从顶部重新渲染变得麻烦,此时我们引入了容器组件.后来我们表明,使用connect()手工编写容器组件比在手写它们更容易- 在这种情况下,connect()负责订阅商店.
  4. 只是包裹Homeconnect()你的情况没有任何效果.connect()生成一个订阅商店的容器组件,但如果您没有指定mapStateToProps参数,它甚至不会订阅商店.使用connect()为使用高效的替换store.getState(),store.subscribe()contextTypes手动.它从来没有让感官使用connect()的东西和打电话store.getState()或指定contextTypes.

所以,再说一遍:

  • store.getState()并且store.subscribe()是低级API.如果你决定使用它们,你必须一起使用它们; 一个没有另一个没有意义.

  • connect()是负责调用getState()subscribe()通过道具为您传递必要信息到子组件.如果你使用connect(),你永远需要store.getState(),store.subscribe()contextTypes.重点connect()是将它们抽象出来.

这些课程教你所有这些工具,向你展示没有魔力.但是通常你不应该使用store.getState()store.subscribe()实际应用.您应该几乎专门使用,connect()除非您有一个非常具体的原因来访问低级API.

我会像这样重写你的代码:

// ProjectSummary is a presentational component
// that takes projects as a prop and doesn't care
// where it comes from.
const ProjectsSummary = ({ projects }) => {
  return (
    <div className="home-projects col-md-10">
      <h3>Projects</h3>
      <ul>
        {projects.map(p => <li key={p.id}>{p.contract.client}</li>)}
      </ul>
    </div>
  )
}

// Home by itself is also a presentational component
// that takes projects as a prop. However we will
// wrap it in a container component below using connect().
// Note that I got rid of inheritance: it's an anti-pattern
// in React. Never inherit components; instead, use regular
// composition and pass data as props when necessary.
const Home = ({ projects }) => (
  <div className="home-page container-fluid">
    <BasePage />
    <HomeLeftBar />
    <HomePageHeader />
    <ProjectsSummary projects={projects} />
  </div>
)

// How to calculate props for <Home />
// based on the current state of the store?
const mapStateToProps = (state) => ({
  projects: state.projects
})

// Generate a container component
// that renders <Home /> with props from store.
export default connect(
  mapStateToProps
)(Home)
Run Code Online (Sandbox Code Playgroud)