image.png
點(diǎn)擊+號(hào),可以異步將store中的數(shù)據(jù)改變,點(diǎn)擊-號(hào)可以同步將store中的數(shù)據(jù)改變兄春,這個(gè)小案例沒(méi)什么邏輯,用react-redux做有種殺蒼蠅用牛刀的感覺(jué)钾腺,但主要是體現(xiàn)react-redux在項(xiàng)目中的基本用法,本人還是個(gè)菜鳥(niǎo)讥裤,計(jì)數(shù)器部分主要參考了這篇文章,講的比較詳細(xì)姻报,很輕松就用代碼實(shí)現(xiàn)了己英,鏈接: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(<App />, 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 (
<Provider store={store}>
<div className="App">
<Counter/>
</div>
</Provider>
);
}
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(
<div>
<h2>Counter</h2>
<div>
<button onClick={this.decrement.bind(this)}>-</button>
<span>{this.props.count}</span>
<button onClick={this.increment.bind(this)}>+</button>
</div>
</div>
)
}
}
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}
}