调度功能,终极版,反应

问题描述:

我学习反应,我有这样的调度功能,终极版,反应

//index.js 
const store = createStore(reducer) 
render(
    <Provider store={store}> 
    <AddTodo /> 
    </Provider>, 
    document.getElementById('root') 
) 

//Apptodo.js 
import React from 'react' 
import { connect } from 'react-redux' 
import { addTodo } from '../actions' 

let AddTodo = ({ dispatch }) => { 
    let input 

    return (
    <div> 
     <form onSubmit={e => { 
     e.preventDefault() 
     if (!input.value.trim()) { 
      return 
     } 
     dispatch(addTodo(input.value)) 
     input.value = '' 
     }}> 
    ....... 

一个例子,为什么没有得到它this.pros.store而只是调用调度()函数?

编辑:它是如何从this.pros中提取dispatch的。是不是对象this.pros.store?在这种情况下,为什么我们不提取store

谢谢。

+0

我相信你会混淆React和Redux的概念。道具是你用React组件获得的。 Redux商店没有任何关联。 react-redux正在连接它们,使您更容易使用Redux的存储方法dispatch()分派操作。 react-redux还可以通过传递函数作为connect()的第一个参数,使商店的状态可以作为道具使用,查看react-redux文档以获取更多信息。 – jabacchetta

+0

谢谢,我会检查它 –

您的addTodo组件可以访问商店的状态和方法(例如dispatch,getState等)。因此,当您通过connect方法与Redux商店建立了联系时,您可以访问商店的状态和方法。

({ dispatch })简单地使用JS destructuring assignmentthis.props对象中提取dispatch

+0

谢谢你,我会阅读关于这个,但为什么我们要提取调度?是不是足够提取商店? –

+0

您无法提取商店。 react-redux的[Provider](https://github.com/reactjs/react-redux/blob/master/docs/api。md)组件通过[connect](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-)来使整个redux存储可用于下面层次结构中的组件, mergeprops-options)方法。所以,这个组件将'store's'方法和状态合并到它的道具中。要访问'dispatch',它可以通过'this.props.dispatch'访问它。 – Rowland

react-redux is the library即将这些方法作为道具传递给您的组件。

dispatch() is the method used to dispatch actions并且触发状态改变到商店。 react-redux只是试图让你方便地访问它。

但是,请注意,如果确实将动作传递给连接功能,则派​​生在道具上不可用。换句话说,在下面的代码中,由于我通过someAction连接,dispatch()已不再支持道具。

但是,这种方法的好处是,您现在可以在您的道具上使用“连接”动作,当您调用它时,会自动为您调度

import React, { PropTypes } from 'react'; 
import { connect } from 'react-redux'; 
import { someAction } from '../myActions'; 

const MyComponent = (props) => { 
    // someAction is automatically dispatched for you 
    // there is no need to call dispatch(props.someAction()); 
    props.someAction(); 
}; 

export default connect(null, { someAction })(MyComponent); 

或者,如果我们使用object destructuring如图你给的例子...

const MyComponent = ({ someAction) => { 
    someAction(); 
}; 

它然而,必须指出的是,你必须调用道具可用的连接动作是非常重要的。如果你试图调用someAction(),你会调用原始的,导入的动作 - 而不是道具上可用的连接动作。下面给出的示例将不更新商店

const MyComponent = (props) => { 
    // we never destructured someAction off of props 
    // and we're not invoking props.someAction 
    // that means we're invoking the raw action that was originally imported 
    // this raw action is not connected, and won't be automatically dispatched 
    someAction(); 
}; 

这是一个常见的错误,人们在使用react-redux时一直运行到所有时间。 Following eslint's no-shadow rule可以帮助你避免这个陷阱。