问题
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 only 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);
回答2:
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 increase readability, it is common use the method mapStateToProps, like this:
const mapStateToProps = state => ({
name: state.nestedObject.innerProperty
})
export default connect(mapStateToProps)(HelloComponent)
来源:https://stackoverflow.com/questions/52857738/mapstatetoprops-for-functional-component