MapStateToProps For Functional Component
Is there any function similar to mapStateToProps so that we can connect Redux state to the functional component in React? Is passing the state as props from parent component the on
Solution 1:
You can definitely use mapStateToProps
with a functional component, the same way you would with a class component.
function MyComponent({ propOne }) {
return <p>{propOne}</p>
}
function mapStateToProps(state) {
return { propOne: state.propOne };
}
export default connect(mapStateToProps)(MyComponent);
Solution 2:
react-redux now has a useSelector method. That's a much cleaner approach for functional components that employ hooks. See: https://react-redux.js.org/next/api/hooks#useselector
Solution 3:
With Hooks you can use something like this
import React from 'react';
import {useDispatch, useSelector} from "react-redux";
const AccountDetails = () => {
const accountDetails = useSelector(state => state.accountDetails);
const dispatch = useDispatch();
return (
<div>
<h2>Your user name is: {accountDetails.username}</h2>
<button onclick={() => dispatch(logout())}>Logout</button>
</div>
);
};
export default AccountDetails;
Solution 4:
You should connect
the component to the store at first.
The connection happen using the connect
HOC provided by the react-redux
package. The first paramter it takes, is a method that, given the global store, returns an object with only the properties you need in this component.
For instance:
import { connect } from 'react-redux'
const HelloComponent = ({ name }) =>
<p>{ name }</p>
export default connect(
globalState => ({ name: globalState.nestedObject.innerProperty })
)(HelloComponent)
To improve readability, it is common use the method mapStateToProps
, like this:
const mapStateToProps = state => ({
name: state.nestedObject.innerProperty
})
export default connect(mapStateToProps)(HelloComponent)
Solution 5:
const CategoryList = (props) => {
return (
<div>
<h3>Category</h3>
<h5>Seçili Kategori:{props.currentCategory.categoryName}</h5>
</div>
);
}
function mapStateToProps(state) {
return {
currentCategory: state.changeCategoryReducer
}
}
export default connect(mapStateToProps)(CategoryList);
Post a Comment for "MapStateToProps For Functional Component"