点击+号,可以异步将store中的数据改变,点击-号可以同步将store中的数据改变,这个小案例没什么逻辑,用react-redux做有种杀苍蝇用牛刀的感觉,但主要是体现react-redux在项目中的基本用法,本人还是个菜鸟,计数器部分主要参考了这篇文章,讲的比较详细,很轻松就用代码实现了,链接:https://daveceddia.com/how-does-redux-work/
以下直接贴代码:
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render( , document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
app.js:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Counter from './view/header/connect'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import reducer from './view/header/reducer'
import thunk from 'redux-thunk'
const store = createStore(reducer,applyMiddleware(thunk))
function App() {
return (
);
}
export default App;
connect.js
import { connect } from 'react-redux'
import Counter from "./counter";
function mapStateToProps(state) {
return {
count: state.count
};
}
export default connect(mapStateToProps, null)(Counter)
counter.js:
import React from 'react'
import { connect } from 'react-redux'
import { incrementAstnc, decrement } from './actions'
class Counter extends React.Component {
constructor() {
super()
}
increment = () => {
this.props.dispatch(incrementAstnc());
}
decrement = () => {
this.props.dispatch(decrement());
}
render() {
return(
Counter
{this.props.count}
)
}
}
export default Counter
reducer.js:
const initialState = {
count: 0
};
function reducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return {
count: state.count + 1
};
case 'DECREMENT':
return {
count: state.count - 1
};
default:
return state
}
}
export default reducer
action.js:
export const incrementAstnc = () => {
return (dispatch) => {
setTimeout(function () {
dispatch(increment())
}, 500)
}
}
export const increment = number => {
return {type: 'INCREMENT', number}
}
export const decrement = number => {
return {type: 'DECREMENT', number}
}