react-redux


使用react-redux的可以将redux与UI组件分开,使组件内不包含任何与redux相关的函数,文件,像store,dispatch,subscribtion这些都不会在UI组件里出现,而所有的状态与派发action的函数都由一个容器组件通过props的形式传递给UI组件,使得UI组件显得更加纯净

使用步骤

1:安装react-redux

$ npm i react-redux

2:使用connect函数为UI组件创建一个容器组件(每一个需要使用react-redux管理状态的UI组件都需要)

3:之前的redux相关文件不需要做改动

App.js

注意这里使用export default 暴露出去的是容器组件,UI组件App则是作为参数传到connect里

connect()()第一个括号接收两个参数,第一个参数用于将redux中状态映射到子组件的props中,第二个参数用于将dispatch操作映射到子组件的Props中,第二个括号接收子组件

可以看到,App组件中没有出现任何redux的东西,所使用的变量函数都是容器组件通过props传来的,同时也实现了无状态组件

import React, { Component } from 'react'
import { connect } from 'react-redux';
import { add, minus } from './redux/action/addOrMinus'
import { getFilms } from './redux/action/getFilmsAction'
import { hide, show } from './redux/action/hideOrShow'
import store from './redux/store'



class App extends Component {
    render() {
        const { add, minus, show, hide, count, films, isShow, getFilms } = this.props

        return (
            

当前值为:{count}

 
{isShow &&
我出来了
}  
    { films.map((item) => { // console.log(store.getState().getFilmsReducer.films) return
  • {item.name}
  • }) }
) } } const mapStateToProps = function (state) { return { count: state.handleAddOrMinusReducer.count, isShow: state.handleShowOrHideReducer.isShow, films: state.getFilmsReducer.films } } const mapDispatchToProps = { hide, show, add, minus, getFilms } export default connect(mapStateToProps, mapDispatchToProps)(App)

index.js

index.js中引入Provider,用于将store传给所有组件,底层是使用context实现的

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './03-react-redux/App';
import reportWebVitals from './reportWebVitals';
import store from './03-react-redux/redux/store'
import { Provider } from 'react-redux'

ReactDOM.render(
  
    
      
    
  ,
  document.getElementById('root')
);
//订阅redux状态的改变来渲染APP组件,使用react-redux时不必加这个,react-redux会自动刷新,加了反而会报错 // store.subscribe(() => { // ReactDOM.render( // // // , // document.getElementById('root') // ); // }) // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();