我正在尝试在我的componentDidMount函数中调用一个函数。它是在我的mapDispatchToProps函数中声明的函数。我正在尝试从函数接收变量以显示在渲染中。相反,我收到此错误:
TypeError:this.props.pageReload(...)。然后不是函数
任何建议都将有助于解决此问题,希望不要重复。我尝试了几种解决方案,但没有成功。
组件级别:
import React from 'react';
import { connect } from 'react-redux';
import { Collapse, Container, Navbar, NavbarBrand, NavbarToggler, NavItem, NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
import { userActions } from '../../../../actions/user.actions';
class InnerHeaderComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
First: "",
Last: ""
};
this.toggle = this.toggle.bind(this);
}
componentDidMount() {
this.props.pageReload()
.then((res) => {
this.setState({
First: res.FirstName,
Last: res.LastName
});
});
}
render() {
return();
}
function mapStateToProps(state) {
const { authentication } = state;
const { user } = authentication;
return {
user
};
}
const mapDispatchToProps = dispatch => ({
pageReload: () => dispatch(userActions.pageReload())
});
export default connect(mapStateToProps, mapDispatchToProps)(InnerHeaderComponent);
动作:
function pageReload() {
return dispatch => {
const user = JSON.parse(localStorage.getItem('user'));
userService._setUserSession(user);
dispatch({ type: userConstants.LOGIN_SUCCESS, user });
console.log(user);
return { FirstName: user.FirstName, LastName: user.LastName };
};
}
答案 0 :(得分:2)
这通常发生在您不从函数中返回诺言时。您的pageReload()
函数似乎没有返回承诺,因此.then()
无效,并且您收到了错误消息。看看Javascript Promise.protoype.then(),尝试一下类似的事情:
function pageReload() {
return dispatch => {
const user = JSON.parse(localStorage.getItem('user'));
userService._setUserSession(user);
dispatch({ type: userConstants.LOGIN_SUCCESS, user });
return Promise.resolve(user)
};
}
然后您可以像这样使用then()
:
this.props.pageReload()
.then(user => {
console.log(user)
});
注意:仅在假设存在问题的情况下才进行测试