# 再續Redux
###### tags: `React`
## 2018 12 17 redux part1
這個筆記會提到`API`的分離, 然後把`API`也透過Redux的方法搞出來
首先老師先示範把檔案分離, 分成`container`和`component`
這邊我就不贅述了, 注意相對路徑不要寫錯而已.
### 有串redux的app長什麼樣子?
- actionTypes
- action => pure JavaScript object
- action creator => 幫助產生action的helper function
```javascript=
// 整組叫做action creator
export const updateNavTab = (tab) => {
// action是指下面這些
return {
type: actionTypes.UPDATE_NAV_TAB,
name: tab
}
}
```
- reducer.js(當一個action進來時,我要怎麼update state)
- index.js中的<Provider /> => 有provider是為了可以傳store, store又是靠reducers建立, 而reducers又是靠combinReducers而來.
- containers (知道有redux的存在)
- components (不知道有redux的存在)
- withRouter要放在container哪一層
### API的部分
原本是這樣
```javascript=
componentDidMount(){
axios.get('https://qootest.com/posts')
....
}
```
但是如果有其他地方也要用的話, 那我這個API就要重複了
所以這樣做不如, 我在開一個`WebAPI`的文件, 把所有會用到的API
都寫在文件裡面.
```javascript=
export const getPosts = () => axios.get('https://qootest.com/posts')
export const getPost = postId =>
axios.get('https://qootest.com/posts/' + postId)
export const deletePost = postId => axios.delete('https://qootest.com/posts/' + postId)
```
那這樣在post_list的頁面就會變成
```javascript=
componentDidMount(){
getPost()
.then(res => this.setState({
posts: res.data
}))
}
```
### API 的response都放在state裡面 => 優化
-> 改成redux, 那這樣我的state就要變成放在store裡面
那就要新的action...
---
額外補充, 何時export的時候要加上大括號?
ans:當你的文件裡面有很多東西要回傳時...
---
### action完成後就要更新reducer
```javascript=
case actionTypes.GET_POSTS:
// 代表說現在要抓這個posts
return {
...globalState,
isLoadingGetPosts: true,
}
case actionTypes.GET_POSTS_SUCCESS:
return {
...globalState,
isLoadingGetPosts: false,
posts:action.data
}
```
### 接下來是container
這邊在新創一個`postListContainer`
在這邊準備好兩個=> `mapStateToProps`, `mapDispatchToProps`
這邊就是在設定state和設定傳給他的props.