是否有类似的功能,mapStateToProps以便我们可以将 Redux 状态连接到 React 中的功能组件?
将状态作为来自父组件的props传递是唯一的解决方案吗?
是否有类似的功能,mapStateToProps以便我们可以将 Redux 状态连接到 React 中的功能组件?
将状态作为来自父组件的props传递是唯一的解决方案吗?
您绝对可以使用mapStateToProps功能组件,就像使用类组件一样。
function MyComponent({ propOne }) {
  return <p>{propOne}</p>
}
function mapStateToProps(state) {
  return { propOne: state.propOne };
} 
export default connect(mapStateToProps)(MyComponent);
react-redux 现在有一个 useSelector 方法。对于使用钩子的功能组件来说,这是一种更简洁的方法。请参阅:https : //react-redux.js.org/next/api/hooks#useselector
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;
您首先应该connect将组件发送到商店。
使用包connect提供的HOC 进行连接react-redux。它需要的第一个参数是一个方法,该方法在给定全局存储的情况下返回一个对象,该对象仅包含您在此组件中需要的属性。
例如:
import { connect } from 'react-redux'
const HelloComponent = ({ name }) =>
    <p>{ name }</p>
export default connect(
    globalState => ({ name: globalState.nestedObject.innerProperty })
)(HelloComponent)
为了提高可读性,通常使用方法mapStateToProps,如下所示:
const mapStateToProps = state => ({
    name: state.nestedObject.innerProperty
})
export default connect(mapStateToProps)(HelloComponent)