javascript 功能组件的 mapStateToProps
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52857738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mapStateToProps for functional component
提问by sumit
Is there any function similar to mapStateToPropsso that we can connect Redux state to the functional component in React?
是否有类似的功能,mapStateToProps以便我们可以将 Redux 状态连接到 React 中的功能组件?
Is passing the state as props from parent component the only solution?
将状态作为来自父组件的道具传递是唯一的解决方案吗?
回答by David
You can definitely use mapStateToPropswith a functional component, the same way you would with a class component.
您绝对可以使用mapStateToProps功能组件,就像使用类组件一样。
function MyComponent({ propOne }) {
return <p>{propOne}</p>
}
function mapStateToProps(state) {
return { propOne: state.propOne };
}
export default connect(mapStateToProps)(MyComponent);
回答by Jason Rice
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
react-redux 现在有一个 useSelector 方法。对于使用钩子的功能组件来说,这是一种更简洁的方法。请参阅:https: //react-redux.js.org/next/api/hooks#useselector
回答by 0xc14m1z
You should connectthe component to the store at first.
您首先应该connect将组件发送到商店。
The connection happen using the connectHOC provided by the react-reduxpackage. 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.
使用包connect提供的HOC 进行连接react-redux。它需要的第一个参数是一个方法,在给定全局存储的情况下,它返回一个对象,该对象仅包含您在此组件中需要的属性。
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:
为了增加可读性,通常使用方法mapStateToProps,如下所示:
const mapStateToProps = state => ({
name: state.nestedObject.innerProperty
})
export default connect(mapStateToProps)(HelloComponent)

