iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 14
0
自我挑戰組

請你當我的好朋友吧!ReactJS!系列 第 14

【DAY 14】狀態儲存在redux的Store中吧!

  • 分享至 

  • twitterImage
  •  

【前言】
  前兩篇我們介紹了actionreducer ,這次不多說廢話直接進到正文吧!
【正文】
  前面一直強調action是描述發生什麼事的物件,reducer是改變state真正執行的函式,並回傳最新的狀態,那這些狀態到底是放在哪裡啊?就是store中。

The Store is the object that brings action and reducer together.

  store主要的功能就是掌管應用程式的狀態,並且有這些任務:

  1. Holds application state:掌管應用程式的狀態
  2. Allows access to state via getState():用getState()讀取state
  3. Allows state to be updated via dispatch(action):用dispatch(action)來更新state
  4. Registers listeners via subscribe(listener):用subscribe(listener)註冊listener
  5. Handles unregistering of listeners via the function returned by subscribe(listener):利用subscribe(listener)回傳的function註銷listener

  在redux的應用程式中,你的store只會有一個而已。

  創建state的方法就是利用createStore(reducer)的方式創建它,而要發送action則利用dispatch(action)來達到,當store收到action時,則會呼叫reducer來幫忙更新state囉。

import { createStore } from 'redux';
import { addTodo } from './actions'
import todoApp from './reducers';

// 利用createStore()創建store的state
const store = createStore(todoApp);


// Dispatch 一些 action
store.dispatch(addTodo('Learn about actions'));
store.dispatch(addTodo('Learn about reducers'));

  這樣子就可以算是一個小型的redux應用程式囉!
  這篇真的是,講超少的XDDDD(超懶惰 哈~


上一篇
【DAY 13】對方聽不懂?那就讓Reducer來幫你一把吧!
下一篇
【DAY 15】利用redux與react搭配在做出一個To do list吧!(上)
系列文
請你當我的好朋友吧!ReactJS!30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言