//组件使用redux的方法;
import React, { Component } from 'react'
import { connect } from 'react-redux';
class playBar extends Component {
constructor(props) {
super(props);
//可以使用state中的数据和方法;放在props中
};
}
}
function mapStateToProps(state) {//数据
return {
playList: state.songs.playList,
};
}
function mapDispatchToProps(dispatch) {//方法
return {
autoChangeCurrentMusic(playList, index) {
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(playBar);//connect
提供redux方法
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './store/index';
function App() {
return (
<Provider store={store}>
<Router>
<Switch>
<Route path='/search' component={Search}/>
<Route path='/songList' component={SongList}/>
</Switch>
</Router>
<PlayBar/>
</Provider>
)
}
export default App;
store/index.js
import { createStore, applyMiddleware, compose } from 'redux';
import ReduxThunk from 'redux-thunk';
import reducer from './reducer';
const composeEnhancers =
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
// Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize...
}) : compose;
const enhancer = composeEnhancers(
applyMiddleware(ReduxThunk),
// other store enhancers if any
);
const store = createStore(reducer, enhancer);
export default store;
reducer.js
import { combineReducers } from 'redux'
import songs from '../components/search/searchSongs/store/index';
const reducer = combineReducers({
songs
});
export default reducer;
songs/index.js
const defaultState = {
index: 0,
playList: [],
currentMusic: {},
showPlayer: false
};
export default (state = defaultState, action) => {
const { type, value } = action;
switch(type) {
case 'SET_INDEX':
return Object.assign({}, state, {
index: value
});
case 'SET_PLAY_LIST':
let playList = state.playList;
playList.push(value);
return Object.assign({}, state, {
playList
});
case 'SET_PLAYLIST_LIST':
return Object.assign({}, state, {
playList: value
});
case 'SET_PLAY_STATUS':
return Object.assign({}, state, {
showPlayer: value
});
case 'SET_CURRENT_MUSIC':
return Object.assign({}, state, {
currentMusic: value
});
case 'DEL_CURRENT_MUSIC':
return Object.assign({}, state, {
playList: value
})
default:
return state;
}
}
来源:CSDN
作者:newway007
链接:https://blog.csdn.net/newway007/article/details/103704788