create-react-app reduxdemo
javascript
yarn add redux -s
java
|-app.js
|-store.js
|-index.jsreact
經過create-react-app建立的項目有許多無用的東西,首先將src目錄清理如上文件內容,而後將index.js精簡以下
chrome
// index.js import React from "react"; import ReactDOM from "react-dom"; import App from "./app"; ReactDOM.render(<App />, document.getElementById("root"));
store.js是redux的核心文件,本文用於學習,不強調代碼細拆分,故reducer和store寫在一塊兒
json
// store.js import { createStore, applyMiddleware } from "redux"; import { composeWithDevTools } from "redux-devtools-extension"; //chrome redux調試工具 // state初始值 const initState = { list: ["a", "b"] }; // reducer格式 const reducer = (state = initState, action) => { const { type, payload } = action; // action的type處理 if (type === "SAVE") { return Object.assign({}, state, payload); } return state; }; /** * 實例化store * 參數1: reducer * 參數2: 中間件 */ export default createStore(reducer, composeWithDevTools(applyMiddleware()));
app.js
// app.js import React, { useState, useEffect } from "react"; import store from "./store"; export default () => { // 獲取store中的state,並放進hook函數,相似this.setState(store.getState()) const [state, setState] = useState(store.getState()); useEffect(() => { // store訂閱函數,當state經過store.dispatch分發action改變時此函數自動執行 store.subscribe(() => { setState(store.getState()); //從新設置組件state的值,使視圖更新 }); }, []); // []表示只執行一次 const { list } = state; const addList = () => { list.push(Date.now()); store.dispatch({ type: "SAVE", payload: { list } }); //分發一個action對象 }; return ( <div> <button onClick={addList}>add</button> <ul> {list.map(v => { return <li key={v}>{v}</li>; })} </ul> </div> ); };
action對象格式爲json對象,而且必須有type屬性不然會報錯誤:Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
redux
攜帶數據通常爲payload屬性,這個沒作強制要求
app