react-redux基本使用

mac2024-03-27  29

Redux 的 React 绑定库是基于 容器组件和展示组件相分离 的开发思想 接触这个不就,如果错误欢迎大家指正

actionType.js

随着项目大型化,所以要抽取出来一个actionType.js文件来记录各种actionType常量

export const SET_CURRENTINDEX ='SET_CURRENTINDEX';

store.js

import { createStore } from 'redux'; import rootReducer from '../reducers'; const store = createStore(rootReducer,window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); export default store;

action.js Action 是把数据从应用(译者注:这里之所以不叫 view 是因为这些数据有可能是服务器响应,用户输入或其它非 view 的数据 )传到 store 的有效载荷。它是 store 数据的唯一来源。一般来说你会通过 store.dispatch() 将 action 传到 store。

import * as types from '../actionTypes'; import store from '../store'; export const IndexActionCreators = { SetCurrentIndex(payload){ return { type :types.SET_CURRENTINDEX, payload } } }

reducers.js Reducers 指定了应用状态的变化如何响应 actions 并发送到 store 的, actions 只是描述了有事情发生了这一事实,并没有描述应用如何更新 state。

import { combineReducers } from 'redux'; import * as types from '../actionTypes'; const rootReaducer = combineReducers({ CurrentIndex }) function CurrentIndex(preState = 0 , action ){ switch( action.type ){ case types.SET_CURRENTINDEX: return action.payload default : return preState; } }

展示组件

//简化代码 import React ,{ Component } from 'react'; import './Player.less'; class Playerextends Component{ constructor( props ){ super(props); } componentDidMount(){ } next(){ let tempIndex=2 this.props.SetCurrentIndex(tempIndex); this.props.SetPlaying(true) } render(){ return( <div className="mus_icon i-right"> <i className="icon-next" onClick={()=>{ this.next() }} ></i> </div> ) } } export default Player;

容器组件 mapStateToProps 是一个函数,用于建立组件跟 store 的 state 的映射关系,他会订阅store的状态改变,在每次 store 的 state 发生变化的时候,都会被调用 mapDispatchToProps 用于建立组件跟store.dispatch的映射关系,定义组件如何发出action,实际上就是调用dispatch这个方法

import { connect } from 'react-redux'; import { IndexActionCreators ,PlayingActionCreators,FullScreenActionCreators ,CurrentSongActionCreators } from '../../actions/idnex.js'; import Player from './player'; // 映射Redux全局的state到组件的props上 const mapStateToProps = (state) => ({ // song: state.song }) // 映射dispatch到props上 const mapDispatchToProps = (dispatch) => ({ SetPlaying:(flag)=>{ dispatch(PlayingActionCreators.SetPlaying(flag)) }, SetCurrentIndex:(index)=>{ dispatch(IndexActionCreators.SetCurrentIndex(index)); }, SetFullScreen:(flag)=>{ dispatch(FullScreenActionCreators.SetFullScreen(flag)) }, SetCurrentSong:(song)=>{ dispatch(CurrentSongActionCreators.SetCurrentSong(song)); } }) // 将UI组件包装成容器组件 export default connect(mapStateToProps, mapDispatchToProps)(Player)

app.js Provider 是react-redux 提供的一个 React 组件,他可以把 store 提供给其子组件

import React , { Component } from 'react'; import { Provider } from "react-redux"; import './App.less'; import store from './store'; class App extends Component{ constructor(props) { super(props); this.state = {}; } render (){ return( <Provider className="App" store={store}> { this.props.children } </Provider> ) } } export default App;
最新回复(0)