Skip to content

Instantly share code, notes, and snippets.

@hacker0limbo
Last active August 22, 2019 13:01
Show Gist options
  • Select an option

  • Save hacker0limbo/45f3b0a3af766cfb14d17ce7034733da to your computer and use it in GitHub Desktop.

Select an option

Save hacker0limbo/45f3b0a3af766cfb14d17ce7034733da to your computer and use it in GitHub Desktop.
使用 react-redux, redux 实现的计数器
/*
使用 react-redux 实现的计数器
*/
import React from 'react'
import ReactDOM from 'react-dom'
import { connect, Provider } from 'react-redux'
import { createStore } from 'redux'
const mapStateToProps = state => {
// 这里的 state 是 store(外部的) state, connect 使得 store 和组件 之间的 props 链接起来, 互相通信
// 当外部 state 发生变化的时候, 调用该方法, 更新当前组件的 props
// props.count = state.count
return {
count: state.count
}
}
const mapDispatchToProps = dispatch => {
// 同理, 将 dispatch 映射到 props 上, 例如 props.increment = dispatch({ type: "INCREMENT" })
return {
increment: () => dispatch({ type: "INCREMENT" }),
decrement: () => dispatch({ type: "DECREMENT" })
}
}
const Counter = connect(mapStateToProps, mapDispatchToProps)((props) => {
// Counter 这个组件实际被包装了以后, 用 connect 得以连接到 redux 的 store
const { increment, decrement } = props
return (
<div>
{props.count}
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</div>
)
})
/*
Store 和 reducer 部分
*/
const initialState = {
count: 0
}
const reducer = (state, action) => {
switch(action.type) {
case "INCREMENT":
return {
count: state.count + 1
}
case "DECREMENT":
return {
count: state.count - 1
}
default:
return state
}
}
const store = createStore(reducer, initialState)
const App = () => {
return (
<div>
<Provider store={store}>
<Counter />
</Provider>
</div>
)
}
const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)
/*
不适用 react-redux 实现的计数器, 需要手动 subscribe
*/
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
const reducer = (state=0, action) => {
switch(action.type) {
case "INCREMENT":
return state + 1
case "DECREMENT":
return state - 1
default:
return state
}
}
const store = createStore(reducer)
const App = props => {
return (
<div>
<span>{props.value}</span>
<button onClick={props.onIncrement}>Increase</button>
<button onClick={props.onDecrement}>Decrease</button>
</div>
)
}
const render = () => {
ReactDOM.render(
<App
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
document.getElementById("root")
)
}
store.subscribe(render)
render()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment