OSDN Git Service

Regular updates
[twpd/master.git] / redux.md
1 ---
2 title: Redux
3 category: React
4 layout: 2017/sheet
5 updated: 2018-01-17
6 weight: -3
7 ---
8
9 ### Creating a store
10
11 ```js
12 import { createStore } from 'redux'
13 ```
14 {: .-setup}
15
16 ```js
17 // Reducer
18 function counter (state = { value: 0 }, action) {
19   switch (action.type) {
20   case 'INCREMENT':
21     return { value: state.value + 1 }
22   case 'DECREMENT':
23     return { value: state.value - 1 }
24   default:
25     return state
26   }
27 }
28 ```
29
30 ```js
31 let store = createStore(counter)
32 ```
33
34 ```js
35 // Optional - you can pass `initialState` as a second arg
36 let store = createStore(counter, { value: 0 })
37 ```
38
39 A store is made from a reducer function, which takes the current `state`, and
40 returns a new `state` depending on the `action` it was given.
41
42 ### Using a store
43
44 ```js
45 let store = createStore(counter)
46 ```
47 {: .-setup}
48
49 ```js
50 // Dispatches an action; this changes the state
51 store.dispatch({ type: 'INCREMENT' })
52 store.dispatch({ type: 'DECREMENT' })
53 ```
54
55 ```js
56 // Gets the current state
57 store.getState()
58 ```
59
60 ```js
61 // Listens for changes
62 store.subscribe(() => { ... })
63 ```
64
65 Dispatch actions to change the store's state.
66
67 ## React Redux
68
69 ### Provider
70
71 ```js
72 import { Provider } from 'react-redux'
73 ```
74 {: .-setup}
75
76 ```js
77 React.render(
78   <Provider store={store}>
79     <App />
80   </Provider>, mountNode)
81 ```
82
83 The `<Provider>` component makes the store available in your React components. You need this so you can use `connect()`.
84
85 ### Mapping state
86
87 ```js
88 import { connect } from 'react-redux'
89 ```
90 {: .-setup}
91
92 ```js
93 // A functional React component
94 function App ({ message, onMessageClick }) {
95   return (
96     <div onClick={() => onMessageClick('hello')}>
97       {message}
98     </div>
99   )
100 }
101 ```
102
103 ```js
104 // Maps `state` to `props`:
105 // These will be added as props to the component.
106 function mapState (state) {
107   return { message: state.message }
108 }
109
110 // Maps `dispatch` to `props`:
111 function mapDispatch (dispatch) {
112   return {
113     onMessageClick (message) {
114       dispatch({ type: 'click', message })
115     }
116   }
117 }
118
119 // Connect them:
120 export default connect(mapState, mapDispatch)(App)
121 ```
122
123 ### Shorthand
124
125 ```js
126 export default connect(
127   (state) => ({
128     message: state.message
129   }),
130   (dispatch) => ({
131     onMessageClick: (message) => {
132       dispatch({ type: 'click', message })
133     }
134   })
135 )(App)
136 ```
137
138 Same as above, but shorter.
139
140 ### Combining reducers
141
142 ```js
143 const reducer = combineReducers({
144   counter, user, store
145 })
146 ```
147
148 Combines multiple reducers into one reducer function. See: [combineReducers](https://redux.js.org/docs/api/combineReducers.html) _(redux.js.org)_
149
150 ## Middleware
151
152 ### Signature
153
154 ```js
155 // noop middleware
156 const logger = store => dispatch => action { dispatch(action) }
157 ```
158
159 ```js
160 const logger = store => {
161   // This function runs on createStore().
162   // It returns a decorator for dispatch().
163
164   return dispatch => {
165     // Runs on createStore(), too.
166     // It returns a new dispatch() function
167
168     return action => {
169       // Runs on every dispatch()
170     }
171   }
172 }
173 ```
174
175 Middlewares are simply decorators for `dispatch()` to allow you to take
176 different kinds of actions, and to perform different tasks when receiving
177 actions.
178
179 ### Applying middleware
180
181 ```js
182 const enhancer = applyMiddleware(logger, thunk, ...)
183 ```
184
185 ```js
186 const store = createStore(reducer, {}, enhancer)
187 ```
188 {: data-line="1"}
189
190 ## References
191 {: .-one-column}
192
193 * [Redux](https://www.npmjs.com/package/redux) _(npmjs.com)_
194 * [React-redux](https://www.npmjs.com/package/react-redux) _(npmjs.com)_
195 * [Usage with React](http://redux.js.org/docs/basics/UsageWithReact.html) _(redux.js.org)_
196 {: .-also-see}