# 排錯
這里會列出常見的問題和對應的解決方案。
雖然使用 React 做示例,但是即使你使用了其它庫,這些問題和解決方案仍然對你有所幫助。
### dispatch action 后什么也沒有發生
有時,你 dispatch action 后,view 卻沒有更新。這是為什么呢?可能有下面幾種原因。
#### 永遠不要直接修改 reducer 的參數
如果你想修改 Redux 給你傳入的 `state` 或 `action`,請住手!
Redux 假定你永遠不會修改 reducer 里傳入的對象。**任何時候,你都應該返回一個新的 state 對象。**即使你沒有使用 [Immutable](https://facebook.github.io/immutable-js/) 這樣的庫,也要保證做到不修改對象。
不變性(Immutability)可以讓 [react-redux](https://github.com/gaearon/react-redux) 高效的監聽 state 的細粗度更新。它也讓 [redux-devtools](http://github.com/gaearon/redux-devtools) 能提供“時間旅行”這類強大特性。
例如,下面的 reducer 就是錯誤的,因為它改變了 state:
```js
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
// 錯誤!這會改變 state.actions。
state.push({
text: action.text,
completed: false
})
return state
case 'COMPLETE_TODO':
// 錯誤!這會改變 state[action.index]。
state[action.index].completed = true
return state
default:
return state
}
}
```
應該重寫成這樣:
```js
function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
// 返回新數組
return [
...state,
{
text: action.text,
completed: false
}
]
case 'COMPLETE_TODO':
// 返回新數組
return state.map((todo, index) => {
if (index === action.index) {
// 修改之前復制數組
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
default:
return state
}
}
```
雖然需要寫更多代碼,但是讓 Redux 變得可具有可預測性和高效。如果你想減少代碼量,你可以用一些輔助方法類似
[`React.addons.update`](https://facebook.github.io/react/docs/update.html) 來讓這樣的不可變轉換操作變得更簡單:
```js
// 修改前
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
// 修改后
return update(state, {
[action.index]: {
completed: {
$set: true
}
}
})
```
最后,如果需要更新 object,你需要使用 Underscore 提供的 `_.extend` 方法,或者更好的,使用 [`Object.assign`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 的 polyfill
要注意 `Object.assign` 的使用方法。例如,在 reducer 里不要這樣使用 `Object.assign(state, newData)`,應該用 `Object.assign({}, state, newData)`。這樣它才不會覆蓋以前的 `state`。
你也可以通過 [對象操作符](recipes/UsingObjectSpreadOperator.md) 所述的使用更多簡潔的語法:
```js
// 修改前:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: true
})
}
return todo
})
// 修改后:
return state.map((todo, index) => {
if (index === action.index) {
return { ...todo, completed: true }
}
return todo
})
```
注意還在實驗階段的特性會經常改變。
同時要注意那些需要復制的深層嵌套的 state 對象。而 `_.extend` 和 `Object.assign` 只能提供淺層的 state 復制。在 [更新嵌套的對象](recipes/reducers/ImmutableUpdatePatterns.md#updating-nested-objects) 章節中會教會你如何處理嵌套的 state 對象。
#### 不要忘記調用 [`dispatch(action)`](api/Store.md#dispatch)
如果你定義了一個 action 創建函數,調用它并**不**會自動 dispatch 這個 action。比如,下面的代碼什么也不會做:
#### `TodoActions.js`
```js
export function addTodo(text) {
return { type: 'ADD_TODO', text }
}
```
#### `AddTodo.js`
```js
import React, { Component } from 'react'
import { addTodo } from './TodoActions'
class AddTodo extends Component {
handleClick() {
// 不起作用!
addTodo('Fix the issue')
}
render() {
return <button onClick={() => this.handleClick()}>Add</button>
}
}
```
它不起作用是因為你的 action 創建函數只是一個**返回** action 的函數而已。你需要手動 dispatch 它。我們不能在定義時把 action 創建函數綁定到指定的 Store 上,因為應用在服務端渲染時需要為每個請求都對應一個獨立的 Redux store。
解法是調用 [store](api/Store.md) 實例上的 [`dispatch()`](api/Store.md#dispatch) 方法。
```js
handleClick() {
// 生效!(但你需要先以某種方式拿到 store)
store.dispatch(addTodo('Fix the issue'))
}
```
如果組件的層級非常深,把 store 一層層傳下去很麻煩。因此 [react-redux](https://github.com/gaearon/react-redux) 提供了 `connect` 這個 [高階組件](https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750),它除了可以幫你監聽 Redux store,還會把 `dispatch` 注入到組件的 props 中。
修復后的代碼是這樣的:
#### `AddTodo.js`
```js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from './TodoActions'
class AddTodo extends Component {
handleClick() {
// 生效!
this.props.dispatch(addTodo('Fix the issue'))
}
render() {
return <button onClick={() => this.handleClick()}>Add</button>
}
}
// 除了 state,`connect` 還把 `dispatch` 放到 props 里。
export default connect()(AddTodo)
```
如果你想的話也可以把 `dispatch` 手動傳給其它組件。
#### 確保 mapStateToProps 是正確的
你可能正確地 diaptching 一個 action 并且將它提到了 reducer 中,但是對應的 state 卻沒有通過 props 正確地傳輸。
## 其它問題
在 Discord [Reactiflux](http://reactiflux.com/) 里的 **redux** 頻道里提問,或者[提交一個 issue](https://github.com/reactjs/redux/issues)。
如果問題終于解決了,請把解法[寫到文檔里](https://github.com/reactjs/redux/edit/master/docs/Troubleshooting.md),以便別人遇到同樣問題時參考。
- 自述
- 介紹
- 動機
- 核心概念
- 三大原則
- 先前技術
- 學習資源
- 生態系統
- 示例
- 基礎
- Action
- Reducer
- Store
- 數據流
- 搭配 React
- 示例:Todo List
- 高級
- 異步 Action
- 異步數據流
- Middleware
- 搭配 React Router
- 示例:Reddit API
- 下一步
- 技巧
- 配置 Store
- 遷移到 Redux
- 使用對象展開運算符
- 減少樣板代碼
- 服務端渲染
- 編寫測試
- 計算衍生數據
- 實現撤銷重做
- 子應用隔離
- 組織 Reducer
- Reducer 基礎概念
- Reducer 基礎結構
- Reducer 邏輯拆分
- Reducer 重構示例
- combineReducers 用法
- combineReducers 進階
- State 范式化
- 管理范式化數據
- Reducer 邏輯復用
- 不可變更新模式
- 初始化 State
- 結合 Immutable.JS 使用 Redux
- 常見問題
- 綜合
- Reducer
- 組織 State
- 創建 Store
- Action
- 不可變數據
- 代碼結構
- 性能
- 設計哲學
- React Redux
- 其它
- 排錯
- 詞匯表
- API 文檔
- createStore
- Store
- combineReducers
- applyMiddleware
- bindActionCreators
- compose
- react-redux 文檔
- API
- 排錯