react-redux不完全指北
阿新 • • 發佈:2020-09-15
1、首先react-redux是用來在元件之間方便傳輸資料以及改變資料的工具
2、常用的react-redux的方法是包含注入已經呼叫
3、首先在最外層包含注入
import { Provider } from 'react-redux' // 全域性包含 ReactDOM.render(<Provider><Main /></Provider>, document.getElementById("main"))
4、建立store(類似於全域性變數)
(1)基本架構
import { createStore, combineReducers } from "redux" // 注入資料與方法 import todos from "./store/todos" import test from "./store/test" // 建立Store與注入 export default createStore(combineReducers({ todos, test }))
(2)資料於方法
// 初始化資料 let initialState: any = 1 // 返回資料,或者根據返回action變化返回內容 export default function (state = initialState, action: any) { switch (action.type) { case 'test': console.log(1) state = state + 1 default: return state } }
4、然後在最外層就可以直接加上store
import myStore from './redux' ReactDOM.render(<Provider store={myStore}><Main /></Provider>, document.getElementById("main"))
5、接著就是每個需要用到store的頁面都要加上connect(需要用到redux建立的全域性變數的)
import { connect } from "react-redux" // 第一個引數是包含全域性引數的函式 // 第二個引數是需要匯入物件的函式 // 這兩個引數到最後都會倒回物件當中 class Test extends React.Component { constructor(props) { super(props); } // 自己匯入的 this.props.addTodo // 自己匯入的 this.props.state render() { return ( <div>1</div> ); } } export default connect( (state: any) => state, { addTodo } )(Main);
6、執行方法需要注意的,需要根據你自己給到內容判斷執行那個方法
// 例如現在就是以type來判斷執行什麼方法 export const addTodo = () => ({ type: 'test', })
7、剛剛講的就是簡單的react-redux的使用方法,當使用react-hook+react-redux,那麼使用起來就會更加的簡單(用到react-hook的createContext)
import { createContext } from 'react' import { createStoreHook, createDispatchHook, createSelectorHook } from 'react-redux' // 整體核心 export const MyContext = createContext(null) // 建立context export const useStore = createStoreHook(MyContext) // 建立獨有的useStore(獲取全域性變數用的) export const useDispatch = createDispatchHook(MyContext) // 建立獨有的dispatch(執行方法用的) export const useSelector = createSelectorHook(MyContext) // 建立獨有的selector(查詢變數用的)
8、注入方式也有所不同
import { MyContext } from '../utils/redux-hook' // 新增一個注入MyContext ReactDOM.render(<Provider context={MyContext} store={myStore}><Main /></Provider>, document.getElementById("main"))
9、使用起來更加方便
// 使用方法 const Test = (props: any) => { const dispatch = useDispatch() return ( <button onClick={() => dispatch({ type: 'test' })}>點選</button> ) } // 查詢元素 const Test = () => { const store = useStore() // 獲取全域性 console.log(store.getState()) // 獲取個別 const counter = useSelector((state: any) => state.test) return ( <div>{counter}</div> ) }