mapStateToProps for functional component

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 07:04:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!