安装react-redux
yarn add react-redux
引入Provider 传入store 类似context
import {Provider} from 'react-redux' import store from '../store/store' render() { const { Component, pageProps } = this.props; return ( <Layout> <Provider store={store}> <Component {...pageProps} /> </Provider> </Layout> ); }
与组件的连接import { connect } from 'react-redux'
import { connect } from 'react-redux'; const Index = ({counter, user, add, rename}) => ( <div> count: {counter.count} name: {user.name} <Button onClick={()=>{add(3)}}>CLICK</Button> <input onChange={e=>rename(e.target.value)} /> </div> ); /** 只要 Redux store 发生改变,mapStateToProps 函数就会被调用。 该回调函数必须返回一个纯对象,这个对象会与组件的 props 合并。 如果你省略了这个参数,你的组件将不会监听 Redux store。 */ function mapStateToProps(state) { return { counter: state.counter, user: state.user }; } // dispatch传入props function mapDispatchToProps(dispatch) { return { add: num=>dispatch({type: 'ADD', num}), rename: name=>dispatch({type: 'UPDATE', name}) }; } // HOC 连接 React 组件与 Redux store。 export default connect(mapStateToProps, mapDispatchToProps)(Index);