2017-03-18 136 views
3

我學習反應,我有這樣的調度功能,終極版,反應

//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

謝謝,我會檢查它 –

回答

2

您的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

4

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可以幫助你避免這個陷阱。