React項目中使用redux

在react項目中使用redux

  1. 安裝redux DevTools和在react項目中安裝redux(翻牆google應用商店安裝)
項目中安裝:yarn add redux
或者 npm install redux -S
又或者 cnpm i redux -S
  1. 創建store
import { createStore } from 'redux'; 
import reducer from './reducer';

const store = createStore(
  reducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;

在這裏插入圖片描述

  1. 創建reduer
const defaultState = { // 默認數據
  inputValue: 'focusdroid',
  list: [ '北京', '上海', ]
}
// reducer 只能接受state,決不能修改state
export default (state = defaultState, action) => {
  console.log(state, action)
  if (action.type === 'change_input_value') {
    const newState = JSON.parse(JSON.stringify(state)); // 深拷貝
    newState.inputValue = action.value;
    return newState; // 返回給store
  }
  return state;
}
  1. 在組件中使用store
import store from '../../store/index'

  constructor(props){
    super(props);
    this.state = store.getState()
    this.handleStoreChange = this.handleStoreChange.bind(this)
    store.subscribe(this.handleStoreChange)
  }
   handleStoreChange () { // 讓store中的值實時同步
    this.setState(store.getState())
  }

  handleInputChange (e) { // 向store中傳遞值
    const action = {
      type:'change_input_value',
      value: e.target.value
    }
    store.dispatch(action)
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章