如何使用react-redux将ReactJS组件正确连接到Redux?

问题描述 投票:0回答:3

我正在尝试在React组件与Redux之间建立我的第一个连接,以从我的节点API收集数据。

目前,这是一个简单的组件,但将来会不断增长,并将衍生出一些子组件,这些子组件将使我能够构建完整的User CRUD界面(列表,编辑,删除,查看等)。 从这种意义上讲,我需要将动作函数连接到对象this.props以便子组件可以继承它。

这是我的代码:

组件UserGrid-将加载用户信息的表数据网格

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as userActions from '../../actions/userActions';

class UserGrid extends React.Component {
  componentWillMount() {
    this.props.fetchUsers();
  }

  render() {
    const mappedUsers = users.map(user => <li>{user.email}</li>);
    return (
            <div>
              <ul>{mappedUsers}</ul>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        users: state.users
    }
}

export default connect(
    mapStateToProps, 
    bindActionCreators(userActions, dispatch)
)(UserGrid);

我的userAction ,将有效地从AJAX调用中加载用户:

import axios from "axios";

export function fetchUsers() {
  return function(dispatch) {
    axios.get("/api/users")
      .then((response) => {
        dispatch({type: "FETCH_USERS_FULFILLED", payload: response.data});
      })
      .catch((err) => {
        dispatch({type: "FETCH_USERS_REJECTED", payload: err});
      })
  }
}

通过此代码,我得到以下错误:

Uncaught ReferenceError: dispatch is not defined
    at Object.<anonymous> (bundle.js:37984)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.<anonymous> (bundle.js:37711)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.<anonymous> (bundle.js:8466)
    at __webpack_require__ (bundle.js:556)
    at fn (bundle.js:87)
    at Object.<anonymous> (bundle.js:588)
(anonymous) @ bundle.js:37984
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:37711
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:8466
__webpack_require__ @ bundle.js:556
fn @ bundle.js:87
(anonymous) @ bundle.js:588
__webpack_require__ @ bundle.js:556
(anonymous) @ bundle.js:579
(anonymous) @ bundle.js:582

将组件连接到所创建的Redux服务的正确方法是什么?

javascript reactjs react-redux
3个回答
1
投票

我认为您不想在这里使用bindActionCreators 。 这是文档所说的(重点是我的):

通常,您应该直接在您的Store实例上调用dispatch 。 如果您将Redux与React一起使用,react-redux将为您提供dispatch函数,因此您也可以直接调用它。

bindActionCreators的唯一用例是当您要将一些动作创建者传递给一个不了解Redux的组件 ,并且您不想将dispatch或Redux存储传递给该组件。

由于这不是您要执行的操作,因此应该直接调用dispatch 。 使用react-redux, connect会将其注入到道具中,因此您可以执行以下操作:

componentWillMount() {
  this.props.dispatch(fetchUsers());
}

1
投票

在您希望连接的组件中,您需要定义函数mapDispatchToProps 。 该函数将调度作为参数,并在connect调用该函数时接收此参数。

这是一些示例代码,这些代码来自我最近的项目之一。

   function mapDispatchToProps(dispatch) {
        return {
            adminActions: bindActionCreators(adminOrdersActions, dispatch),
            schoolActions: bindActionCreators(schoolOrdersListActions, dispatch),
            userActions: bindActionCreators(userActions, dispatch)
        };
    }

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

现在定义了分发。

编辑:为澄清起见,现在您可以通过以下语法访问操作。 this.props.actions.yourAction或您在mapDispatchToProps调用的任何操作。

这是您对我所做的更改的代码:

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import * as userActions from '../../actions/userActions';

class UserGrid extends React.Component {

  componentWillMount() {
    console.log(JSON.stringify(this.props));

    //this.props.fetchUsers();
    this.props.actions.fetchUsers();
  }

  render() {

    const mappedUsers = users.map(user => <li>{user.email}</li>)

    return (
            <div>
            <ul>{mappedUsers}</ul>
            </div>
        )
    }
}

function mapStateToProps(state) {
    return {
        users: state.users
    }
}

function mapDispatchToProps(dispatch) {
    // this function will now give you access to all your useractions by simply calling this.props.actions.
    //if the key of this object would not be actions, but rather foobar, you will get your actions by 
    // calling this.props.foobar
    return {
        actions: bindActionCreators(userActions, dispatch)
    }
}

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

1
投票

正如Jordan所说,我不会使用bindActionCreators

您的组件应如下所示:

import React  from 'react';
import { connect } from 'react-redux';

import myAction from './my-action';

class MyComponent extends React.Component {

    componentDidMount() {
        this.props.myAction();
    }

    render() {
        return "Hi!"
    }

}

const mapStateToProps = (state) => ({
    myState: state.myState
});

const mapDispatchToProps = (dispatch) => ({
    myAction: () => dispatch(myAction())
});

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
© www.soinside.com 2019 - 2024. All rights reserved.