函式元件中react-redux基本使用
阿新 • • 發佈:2021-08-25
安裝:yarn add redux react-redux
1、定義store檔案 store.js
import { createStore } from 'redux'; import reducer from './reducer'; const configureStore = () => createStore(reducer) export default configureStore;
2、定義reducer檔案 reducer.js
const initialState = { menuName: '首頁', current: '123123資料' }// eslint-disable-next-line import/no-anonymous-default-export export default (state = initialState, action) => { console.log('action', action) // 使用dispatch呼叫action中的方法會觸發更新state 獲取到action之後根據type的不同來更改不同的值 類似於action:{type: "SWITCH_MEUN", menuName: "訂單管理"} switch (action.type) { case'SWITCH_MEUN': return { ...state, // 儲存上一個狀態值的寫法 menuName: action.menuName } case 'SWITCH_CURRENT': return { ...state, // 儲存上一個狀態值的寫法 current: action.current } default:return { ...state } } }
3、使用Provider包裹 index.js (入口檔案)
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { Provider } from 'react-redux' import configureStore from './store/index' const store = configureStore() ReactDOM.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
4、實際使用
使用useDispatch呼叫action修改資料
使用useSelector獲取資料
import React from 'react' import {useDispatch, useSelector} from 'react-redux' export default function Header() { const dispatch = useDispatch() const current = useSelector((state) => { return state.current }) const changeCurrent = ()=> { dispatch({ type: 'SWITCH_CURRENT', current: '修改後的current' }) } return ( <div> 子元件 <h3>{current}</h3> <button onClick={changeCurrent}>修改current</button> </div> ) }