普通的react组件是无法与redux交互的,因此需要react-Redux来对react组件加工。react redux主要提供了Provider与connect方法

常见示例:
import React, {Component, PropTypes} from 'react' import ReactDOM from "react-dom"; import thunk from 'redux-thunk' import {createStore, applyMiddleware, combineReducers} from 'redux' import {Provider, connect} from 'react-redux' function postsByReddit(state = [], action) { switch (action.type) { case "RECEIVE_POSTS": return action.posts; default: return state } } const rootReducer = combineReducers({ posts: postsByReddit }) const middleware = [thunk]; const store = createStore( rootReducer, applyMiddleware(...middleware) ) class Posts extends Component { render() { return ( <ul> {this.props.posts.map((post, i) => <li key={i}>{post.title}</li> )} </ul> ) } } class App extends Component { constructor(props) { super(props) } componentDidMount() { const {dispatch} = this.props function fetchPosts() { return (dispatch, getState) => { return fetch(`https://www.reddit.com/r/reactjs.json`) .then(response => response.json()) .then( json => { dispatch({ type: "RECEIVE_POSTS", posts: json.data.children.map(child => child.data), receivedAt: Date.now() }) //console.log(getState()) } ) } } dispatch(fetchPosts()) } render() { const {posts} = this.props const isEmpty = posts.length === 0 return ( <div> <Posts posts={posts}/> </div> ) } } function mapStateToProps(state) { const {posts} = state return { posts } } var Root = connect(mapStateToProps)(App) ReactDOM.render( <Provider store={store}> <Root /> </Provider>, document.getElementById('root') )
<Provider store>
Provider方法会在react组件外边包一层名为provider的组件,使其所有子组件共享store提供的方法。
其原理可以参考:React组件数据共享
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
连接 React 组件与 Redux store。
连接操作不会改变原来的组件类,反而返回一个新的已与 Redux store 连接的组件类。组件类内部会对store.dispach进行监听,当store中state发生变化触发更新组件操作。
- [mapStateToProps(state, [ownProps]): stateProps] (Function): 如果定义该参数,组件将会监听 Redux store 的变化。任何时候,只要 Redux store 发生改变,mapStateToProps 函数就会被调用。该回调函数必须返回一个纯对象,这个对象会与组件的 props 合并。如果你省略了这个参数,你的组件将不会监听 Redux store。如果指定了该回调函数中的第二个参数 ownProps,则该参数的值为传递到组件的 props,而且只要组件接收到新的 props,mapStateToProps 也会被调用(例如,当 props 接收到来自父组件一个小小的改动,那么你所使用的 ownProps 参数,mapStateToProps 都会被重新计算)。
- [mapDispatchToProps(dispatch, [ownProps]): dispatchProps] (Object or Function): 如果传递的是一个对象,那么每个定义在该对象的函数都将被当作 Redux action creator,而且这个对象会与 Redux store 绑定在一起,其中所定义的方法名将作为属性名,合并到组件的 props 中。如果传递的是一个函数,该函数将接收一个 dispatch 函数,然后由你来决定如何返回一个对象,这个对象通过 dispatch 函数与 action creator 以某种方式绑定在一起(提示:你也许会用到 Redux 的辅助函数 bindActionCreators())。如果你省略这个 mapDispatchToProps 参数,默认情况下,dispatch 会注入到你的组件 props 中。如果指定了该回调函数中第二个参数 ownProps,该参数的值为传递到组件的 props,而且只要组件接收到新 props,mapDispatchToProps 也会被调用。
- [mergeProps(stateProps, dispatchProps, ownProps): props] (Function): 如果指定了这个参数,mapStateToProps() 与 mapDispatchToProps() 的执行结果和组件自身的 props 将传入到这个回调函数中。