将 react-redux 与 connect() 和 {...this.props} 一起使用

IT技术 reactjs nested redux react-redux
2021-05-19 23:23:57

我不知道如何制定正确的解决方案,当我想从其他组件调用容器中的操作时,顺便说一下,我想使用扩展运算符,因为我需要在组件中传递太多参数并且不想描述他们都是。

我知道我可以通过 props 从 redux store 传递所有 props,就像 Menu 中的这个例子,但是我的组件太嵌套了,我必须在 nest 的八个组件中发送 props

render() {

        return (
            <div className="wrapper">
                <Menu {...this.props} />
            </div>
        );

    }

}

const mapStateToProps = reduxStore => (
    {
        app: reduxStore.app
    }),

    mapDispatchToProps = dispatch => ({appActions: bindActionCreators(appActions, dispatch)});

export default connect(mapStateToProps, mapDispatchToProps)(App);

所以,我决定将我的嵌套组件与 redux 存储连接起来,因为我需要在我的嵌套组件中使用主容器组件中的存储和操作。但是这个解决方案不起作用,因为我对嵌套组件使用了扩展运算符。

render() {

        return <Link activeClassName='active' onClick={this.props.appActions.closeMenu} {...this.props} />;

    }

使用扩展运算符非常重要,因为组件从其父组件获得太多不同的参数,如果我不使用 {...this.props},我必须这样写:

render() {

        const { to, onlyActiveOnIndex, className, specialIcons } = this.props;

        return <Link activeClassName='active' onClick={this.props.appActions.closeMenu} to={to} specialIcons={specialIcons} onlyActiveOnIndex={onlyActiveOnIndex} className={className} >{this.props.children}</Link>;

    }

而且,我必须连接到公共 redux 存储,当我连接时,发生错误,因为我的组件使用 {...this.props} 并且它获取所有props,包括来自容器和组件的动作不知道拿他们怎么办。我找到了这个问题的一个解决方案,但我不确定它是否是正确的变体。我使用扩展运算符克隆props,但从公共存储中删除包含新功能(操作)的属性。

render() {

        let oldProps = {...this.props};
        delete oldProps.appActions;
        delete oldProps.app;

        return <Link activeClassName='active' onClick={this.props.appActions.closeMenu} {...oldProps} >{this.props.children}</Link>;

    }

}

const mapState = reduxStore => ({app: reduxStore.app}),
    mapDispatchToProps = dispatch => ({appActions: bindActionCreators(appActions, dispatch)});

export default connect(mapState, mapDispatchToProps)(NavLink);

我猜我不了解 react-redux 中的一些基本和全局的东西,或者我使用了不好的做法。可能我应该在 React 中使用高阶组件?但现在我不知道如何让它变得更好。

1个回答

这是一个功能示例。我是为个人项目制作的。出于示例的目的,我删除了无用的代码。你可能想要得到的东西是 eslint,它会告诉你人们在编码时犯的基本错误。

例如,它会说你已经声明了你的 PropTypes。在您的代码中,它在哪里说明了什么是应用程序?确定它来自 reduxStore.app 但它是什么样的 PropTypes?

此外,您不应将所有 reduxStore 状态链接到您的组件。你应该只导入你真正需要的东西。在我的例子,我只导入usersstate.app.users如果我有更多,或者想要 reducer 状态的所有元素,我会单独导入所有元素,然后像这样声明props:

 Home.propTypes = {
        users: PropTypes.object.isRequired,
        actions: {
            load: PropTypes.func.isRequired,
        },
    };

因为 JavaScript 不是类型化语言,所以上面的 PropTypes 可以帮助您进行类型化验证。您还可以看到actions包含您AppActions在案例中导入的所有功能的props

要从后面的操作中了解如何使用该功能,请查看我的 componentWillMount()

    import React, { Component, PropTypes } from 'react';
    import { ListView} from 'react-native';
    import { connect } from 'react-redux';
    import { bindActionCreators } from 'redux';

    import * as app from '../../actions/appActions';

    const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });

    class Home extends Component {

        constructor(props) {
            super(props);
            this.state = {
                dataSource: ds.cloneWithRows(props.users.toJS()),
            };
        }

        componentWillMount() {
            this.props.actions.load();
        }

        componentWillReceiveProps(nextProps) {
            if (this.props.users !== nextProps.users) {
                this.setState({
                    dataSource: ds.cloneWithRows(nextProps.users),
                });
            }
        }

        render() {
            return (
                  <ListView
                      dataSource={this.state.dataSource}
                      enableEmptySections
                      renderRow={
                          (rowData) => <User haveLunch={rowData.haveLunch} name={rowData.name} />
                      }
                  />
            );
        }
    }

    Home.propTypes = {
        users: PropTypes.object.isRequired,
        actions: {
            load: PropTypes.func.isRequired,
        },
    };

    function mapStateToProps(state) {
        return {
            users: state.app.users,
        };
    }

    function mapDispatchToProps(dispatch) {
        return {
            actions: bindActionCreators(app, dispatch),
        };
    }

export default connect(mapStateToProps, mapDispatchToProps)(Home);

希望这会帮助你;)