标签:patch cer hang code 失效 pen const 用法 reducer
最近用react写项目的时候,开始复习之前学过的redux,记录一下一些坑,以防忘记
我现在的redux目录下有这么些东西
首先是index.js
import { createStore } from ‘redux‘ import player from ‘./player_reducer‘ let store = createStore(player) export default store
然后是player.js
import { PLAY_LOCALMUSIC,CAN_CHANGE_PLAY_STATUS,CANNT_CHANGE_PLAY_STATUS,OPEN_PLAY_DETAIL,PLAY_STATUS } from ‘./actionType‘ const defaultState = { playlocalIndex:0, playtype:1, canchangeplaystatus:false, open_play_detail:false, play_status:false, playingdata:{} } export default function player(state = defaultState, action) { //函数体
return state }
然后是封装的actioncreater和actiontype
export const PLAY_LOCALMUSIC = ‘play_localmusic‘ export const CAN_CHANGE_PLAY_STATUS = ‘can_change_play_status‘
import { PLAY_LOCALMUSIC,CAN_CHANGE_PLAY_STATUS,CANNT_CHANGE_PLAY_STATUS,OPEN_PLAY_DETAIL,PLAY_STATUS } from "./actionType"; export const play_localmusic = (index,play_type) => ({ type:PLAY_LOCALMUSIC, index:index, play_type:play_type }) export const canchangeplaystatus = () => ({ type:CAN_CHANGE_PLAY_STATUS, })
现在一切正常,当更改store触发函数后打印此时的sotre.getState(),得到的结果是这样的
import { createStore } from ‘redux‘ import neteasecloudmusic from ‘./app‘ let store = createStore(neteasecloudmusic) export default store
现在由于项目变复杂需要多个reducer共通管理store,则使用了combinereducers,更改如下,新建app.js
import { combineReducers } from ‘redux‘; import player from ‘./player_reducer‘; const neteasecloudmusic = combineReducers({ player }) export default neteasecloudmusic;
修改index.js
import { createStore } from ‘redux‘ import neteasecloudmusic from ‘./app‘ let store = createStore(neteasecloudmusic) export default store
player.js保持不动,由于我到这个时候没有使用connect,直接使用store.getState()进行的渲染,所以这时候关于redux的所有功能都会失效,原因在于这个时候再次打印store.getState()
这个时候的state变成了一个对象(之前也是一个对象),只不过现在被分割出来了
然后就是connect的用法,在组件页面引入connect
import { connect } from ‘react-redux‘
然后组件的export做一点改动
const mapstatetoprops = (state) => { return{ canchangeplaystatus:state.player.canchangeplaystatus, playtype:state.player.playtype, playlocalIndex:state.player.playlocalIndex, } } const mapdistoprops = (dispatch) => { return{ open_play_detail (data) { console.log(‘为什么啊‘) const action = openplaydetail(true,data) dispatch(action) } } } export default connect(mapstatetoprops,mapdistoprops)(Player)
通过connect,将store的数据以及dispatch方法绑定在了组件的props上,可以直接通过this.props访问到store里的数据,不用使用store.getState(),而且props会根据变化渲染页面
关于redux和react-redux使用combinereducers之后的问题
标签:patch cer hang code 失效 pen const 用法 reducer
原文地址:https://www.cnblogs.com/zxh2459917510/p/11165217.html