07.redux与react配合使用
stark.redux.js
import { createStore } from 'redux'
const EAT = 'eat'
const HUNGRY = 'hungry'
// reducer
export const weight = (state = 160 , action) => {
switch (action.type) {
case EAT:
return state + 10
case HUNGRY:
return state - 10
default:
return 160
}
}
// action
export const eat = () => {
console.log('stark wang 正在吃山珍海味')
return {type: EAT}
}
export const hungry = () => {
console.log('饿了一天')
return {type: HUNGRY}
}
App.js
import React from 'react'
import logo from './logo.svg'
import './App.css'
import { eat, hungry } from './stark.redux'
class App extends React.Component {
render () {
const store = this.props.store
const num = store.getState()
return (
<div className='App'>
<header className='App-header'>
<img src={logo} className='App-logo' alt='logo' />
<p>
【redux完全指南】系列1:从入门到会用
<br></br>
hi gusy, I am stark
</p>
<a
className='App-link'
href='https://shudong.wang'
target='_blank'
rel='noopener noreferrer'>跟着stark wang 学redux</a>
<h2>stark wang 当前的体重为{num}斤</h2>
<button onClick={() => {store.dispatch(eat())}}>
吃了一坨山珍海味
</button>
<button onClick={() => {store.dispatch(hungry())}}>
饿了一天
</button>
</header>
</div>
)
}
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { createStore } from 'redux'
import { weight } from './stark.redux'
const store = createStore(weight)
const render = () =>{
ReactDOM.render(<App store={store} />, document.getElementById('root'));
}
render()
store.subscribe(render)
// 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();