Redux, react-router Access Hooks
With the release of the React hooks, the React ecosystem also updates the related pair’s functional component hooksAPIs
React-Redux
👉React-Redux7.1 provides useSelector, useActions, useDispatch, and useStore instead of connect() advanced components
useSelector
const result: any = useSelector(selector: Function, equalityFn? : Function)
Copy the code
Allows you to extract data from Redux storage state using the selector feature
The selector function should be pure because it can be executed multiple times at any point in time
Conceptually, the selector function takes roughly the same parameters as connect’s mapStateToProps. When the selector function is called, it will be passed the entire state of the Redux store as the only argument. Every time a function component is rendered, the selector function is called. UseSelector () will also subscribe to Redux’s sotre and will be executed every time you dispatch an action
Note: When an action is dispatched, useSelector() references (===) the result of the last call to the selector function with the result of the current call. If it is different, the component is forced to re-render. If it is, it will not be re-rendered
Optimization: Make shallow comparisons
import { useSelector, shallowEqual } from 'react-redux'
export function useShallowEqualSelector(selector) {
return useSelector(selector, shallowEqual)
}
Copy the code
useActions
Deprecated, not recommended (actionCreater)
useDispatch
const dispatch = useDispatch()
Copy the code
useStore
const store = useStore()
Copy the code
Used in the dva
Dva supports hooksAPI in 2.6.0-beta.6 and can be used directly
import { useSelector, useDispatch } from 'dva';
Copy the code
React-Router
👉 react-router provides useHistory, useNavigate, useLocation, useParams, useRoutes,
useNavigate
// v5
import { useHistory } from 'react-router-dom';
function MyButton() {
let history = useHistory();
function handleClick() {
history.push('/home');
};
return <button onClick={handleClick}>Submit</button>;
};
Copy the code
// v6
import { useNavigate } from 'react-router-dom';
function MyButton() {
let navigate = useNavigate();
function handleClick() {
navigate('/home');
};
return <button onClick={handleClick}>Submit</button>;
};
Copy the code
useLocation
let location = useLocation();
Copy the code
useParams
const { flag } = useParams();
Copy the code
useRoutes
// v6
function App() {
let element = useRoutes([
{ path: '/', element: <Home /> },
{ path: 'dashboard', element: <Dashboard /> },
{ path: 'invoices'.
element: <Invoices />,
children: [
{ path: ':id', element: <Invoice /> },
{ path: 'sent', element: <SentInvoices /> }
]
},
/ / redirection
{ path: 'home', redirectTo: '/' },
// 404 not found
{ path: The '*', element: <NotFound /> }
]);
return element;
}
Copy the code