Kuidas toimub andmete vahetamine Redux ja React komponendi vahel?
sobes.tech AI
Vastus AI-lt
Interaction is carried out through three main mechanisms: connect, useSelector, and useDispatch.
-
connect (for class components, but can also be used with functional components): Connects a React component to the Redux store. It takes two functions:
mapStateToPropsandmapDispatchToProps.mapStateToProps(state, ownProps): Receives the state from the store and the component's props, returns an object with state data that will be accessible via props.mapDispatchToProps(dispatch, ownProps): Receives thedispatchfunction and the component's props, returns an object with action functions that will be accessible via props for dispatching actions to the store.- The return value of
connectis a higher-order function that wraps the component.
// Code fragment import { connect } from 'react-redux'; const mapStateToProps = (state) => ({ count: state.counter.count }); const mapDispatchToProps = (dispatch) => ({ increment: () => dispatch({ type: 'INCREMENT' }) }); const MyComponent = ({ count, increment }) => ( <div> <p>{count}</p> <button onClick={increment}>Increment</button> </div> ); export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); -
useSelector (hook for functional components): Allows extracting data from the Redux store state. It takes a selector function that receives the current Redux state as an argument and returns the desired data fragment.
// Code fragment import { useSelector } from 'react-redux'; const MyFunctionalComponent = () => { const count = useSelector(state => state.counter.count); return ( <div> <p>{count}</p> </div> ); }; -
useDispatch (hook for functional components): Returns a reference to the
dispatchfunction from the Redux store. It is used to send (dispatch) actions to the store.// Code fragment import { useDispatch } from 'react-redux'; const MyFunctionalComponent = () => { const dispatch = useDispatch(); const handleIncrement = () => { dispatch({ type: 'INCREMENT' }); }; return ( <button onClick={handleIncrement}>Increment</button> ); };
In the end, data from Redux (obtained via connect or useSelector) become accessible in the component as props or variables, and functions for changing the state (connect or useDispatch) are used to send actions, which are processed by reducers and update the store state. When the relevant part of the state changes, the connected component automatically re-renders with the new data.