无法在组件内部使用Redux操作

时间:2019-07-27 09:14:12

标签: javascript reactjs redux single-page-application

加载时我有一个组件,我想调度一个动作,我使用了mapDispatchToProps,但是我无法在props中访问该动作,但是它可以在其他组件中使用,但是每当我从componentDidMount调用此函数时,它都会给我类型错误:没有这样的功能,我检查了一下……我的代码中没有错别字,即使那样我似乎也无法正常工作。

import React, { Component } from "react";
import { connect } from "react-redux";
import { getUserDetails } from "../../store/actions/usersActions";

export class UserDetails extends Component {
  state = {
    user: this.props.userDetails
  };

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps.userDetails !== this.props.userDetails) {
      this.setState({
        user: this.props.userDetails
      });
    }
  }

  componentDidMount() {
    console.log(this.props);
    //this.props.getUserDetails(this.props.match.params.username);
  }

  render() {
    const { user } = this.state;

    return user ? (
      <div className="userDetails">
        <p>{user.username}</p>
      </div>
    ) : (
      <div className="userDetails" />
    );
  }
}

const mapStateToProps = state => {
  return {
    userDetails: state.user.userDetails
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getUserDetails: username => dispatch(getUserDetails(username))
  };
};

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

componentDidMount() {
  19 |    console.log(this.props);
> 20 |    this.props.getUserDetails(this.props.match.params.username);
     | ^  21 |  }
  22 | 
  23 |  render() {
View compiled
commitLifeCycles
D:/Web Projects/min-social-media/client/node_modules/react-dom/cjs/react-dom.development.js:18109
  18106 |       !(instance.state === finishedWork.memoizedState) ? warning$1(false, 'Expected %s state to match memoized state before ' + 'componentDidMount. ' + 'This might either be because of a bug in React, or because ' + 'a component reassigns its own `this.props`. ' + 'Please file an issue.', getComponentName(finishedWork.type) || 'instance') : void 0;
  18107 |     }
  18108 |   }
> 18109 |   instance.componentDidMount();
        | ^  18110 |   stopPhaseTimer();
  18111 | } else {
  18112 |   var prevProps = finishedWork.elementType === finishedWork.type ? current$$1.memoizedProps : resolveDefaultProps(finishedWork.type, current$$1.memoizedProps);

0 个答案:

没有答案