mapStateToProps用于功能组件

sum*_*mit 5 javascript reactjs redux

是否有任何类似的函数mapStateToProps可以将Redux状态连接到React中的功能组件?

从父组件传递状态作为道具唯一的解决方案?

Dav*_*vid 23

您可以使用mapStateToProps功能组件,就像使用类组件一样.

function MyComponent({ propOne }) {
  return <p>{propOne}</p>
}

function mapStateToProps(state) {
  return { propOne: state.propOne };
} 

export default connect(mapStateToProps)(MyComponent);
Run Code Online (Sandbox Code Playgroud)

  • @Pratap props 和 mapStateToProps 的本质区别在于数据的来源。在mapStateToProps中,数据源是redux store。而在 props 中,数据源是父组件。当组件可以了解 redux store 时使用 mapStateToProps ,当它是一个独立的 UI/可重用组件时使用 props 。 (2认同)

Jas*_*ice 12

react-redux 现在有一个 useSelector 方法。对于使用钩子的功能组件来说,这是一种更简洁的方法。请参阅:https : //react-redux.js.org/next/api/hooks#useselector

  • 这太棒了.. useDispatch 和 useSelector (3认同)

sno*_*lli 11

使用 Hooks 你可以使用这样的东西

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;
Run Code Online (Sandbox Code Playgroud)