- 安裝react-redux
npm install --save react-redux - 只需兩步即可將Redux連接到React中
-
在所有組件的頂層使用Provider組件給整個程序提供store.
import { Provider } from 'react-redux';
....ReactDOM.render( <Provider store={store}> ... </Provider> )
-
-
使用connect()將 state 和 action創建的函數綁定到組件中
import Counter from ' ./components/Counter';//導入Reducer
import { connect } from 'react-redux';
import * as ActionCreators from './actions';//導入action
export default connect(
state => ({counter: state.counter}),
ActionCreators
)(Counter);第一個參數是參數state的函數,該函數返回的對象被合并到組件的props中。
第二個參數將所有的action創建函數傳到了組件的同名屬性(比如increment被傳遞到了props.increment)中,同時為每個action創建函數隱性綁定了dispatch方法,可直接通過props調用這些action創建函數,無需再使用dispatch來發起它們。