生命周期方法无法按预期工作

时间:2018-09-15 19:17:02

标签: reactjs redux

我想检查当前用户是否跟随该用户。我正在'componentDidMount'中运行此功能。但我收到以下错误:

UserProfile.js:29未捕获(承诺)TypeError:无法读取未定义的属性“ includes”

根据文档,componentdidmount在第一次渲染后触发。在这里,我应该通过componentWillMount获取第一个渲染中的值。但这没有发生。

import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import axios from 'axios';
import PostListItem from './PostListItem';
import {getUser, addFollower, addFollowing, removeFollower, removeFollowing} 
from '../actions/user';
class UserProfile extends React.Component{
constructor(props){
    super(props);
     this.state = {
        user:'',
        isFollowed: false
    } 
}

componentWillMount(){
    console.log(this.props.match.params._id);
    axios

.get(`http://localhost:5000/api/user/${this.props.match.params._id}`)
        .then(res => {
            console.log(res.data);
            this.setState({user: res.data});
            this.props.dispatch(getUser(res.data));
        }); 
}

componentDidUpdate(){
    if(this.state.user.following.includes(this.props.currentUser.uid)){
        this.setState({isFollowed: true});
    }
}


render(){
    return(
        <div>
            <div>
                <div className="User-description">
                  {this.state.user.avatar}
                  <img src={this.state.user.avatar} alt= 
{this.state.user.name}/>
                </div>
                {(this.props.currentUser.uid === this.state.user._id) ?
                    <Link to={`/${this.state.user._id}/edit`}>Edit 
Profile</Link> :
                    <button 
                    onClick={this.onFollow}>
                    {this.state.isFollowed? 'Following': 'Follow'}
                </button>
                }
            </div>
)
}

const mapStateToProps = (state) =>{
console.log(state);
 return{ 
     currentUser: state.auth
    // user: state.user.find(user => user._id === props.match.params._id)
 }
};  

export default connect(mapStateToProps)(UserProfile);

2 个答案:

答案 0 :(得分:1)

请记住,以下是您代码中的异步计算:

axios.get(`http://localhost:5000/api/user/${this.props.match.params._id}`)
        .then(res => {
            console.log(res.data);
            this.setState({user: res.data});
            this.props.dispatch(getUser(res.data));
        }); 

当处理队列中的其余事件时,您的Promise处理程序将最终设置状态。这里componentDidMount()componentDidUpdate()render()之后执行。您的then处理函数直到那时才执行,因此user.following并未处于您的状态。 尝试检查字段following是否存在,然后继续进行操作,因为最终它将被设置:

componentDidUpdate(){

    if(this.state.user.following && this.state.user.following.includes(this.props.currentUser.uid)){
        this.setState({isFollowed: true});
    }
}

答案 1 :(得分:0)

在使用user之前检查followingincludes

if(this.state.user && 
   this.state.user.following.includes(this.props.currentUser.uid)){