渲染时数组丢失

时间:2018-10-21 17:21:44

标签: reactjs material-ui

我有一个可以正常运行的MYProfile.js文件。我已经删除了导入和样式部分。

class MyProfile extends Component {
  constructor({match}) {
    console.log("constructor");
    super()
    this.state = {
      user: '',
      redirectToSignin: false
    };
    this.match = match;
  }

  init = (userId) => {
    console.log("init");
    const jwt = auth.isAuthenticated();
    read({
      userId: userId
    }, {t: jwt.token}).then((data) => {
      if (data.error) {
        this.setState({redirectToSignin: true})
      } else {
        console.log(data);
        this.setState({user: data});
        console.log(this.state.user.roles);
      }
    })
  }

  componentWillReceiveProps = (props) => {
    console.log("componentWillReceiveProps");
    this.init(props.match.params.userId)
  }

  componentDidMount = () => {
    console.log("componentDidMount");
    this.init(this.match.params.userId)
  }

  render() {
    console.log("render");
    const {classes} = this.props;
    const redirectToSignin = this.state.redirectToSignin;
    if (redirectToSignin) { return <Redirect to='/signin'/> }
    return (
      <Paper className={classes.root} elevation={4}>
        <Typography type="title" className={classes.title}>
          Profile
        </Typography>
        <List dense>
          <ListItem>
            <ListItemAvatar>
              <Avatar>
                <Person/>
              </Avatar>
            </ListItemAvatar>
            <ListItemText primary={this.state.user.name} secondary={this.state.user.email} /> 
          </ListItem>
          <Divider/>
          <ListItem>
            <Typography>Your Profile ID: {this.state.user._id}</Typography>
          </ListItem>
          <ListItem>
            <Typography>You are assigned the following Roles: </Typography>
          </ListItem>
          <Divider/>
          <ListItem>
            <ListItemText primary={"Joined: " + (
              new Date(this.state.user.created)).toDateString()}/>
          </ListItem>
        </List>
      </Paper>
    )
  }
}

MyProfile.propTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(styles)(MyProfile)

我在控制台上得到以下输出

MyProfile.js?dec7:33 constructor
MyProfile.js?dec7:69 render
MyProfile.js?dec7:64 componentDidMount
MyProfile.js?dec7:43 init
MyProfile.js?dec7:51 {status: "New", roles: Array(3), created: "2018-09-20T16:14:58.110Z", _id: "5ba3c7829708249ed4c3ce5b", name: "avinash", …}
MyProfile.js?dec7:69 render
MyProfile.js?dec7:53 (3) [{…}, {…}, {…}]

这些角色向我展示:

  (3) [{…}, {…}, {…}]
  0: {Module: "Core", Role: "Owner"}
  1: {Module: "Core", Role: "Administrator"}
  2: {Module: "Core", Role: "Regular User"}
  length: 3
  __proto__: Array(0)

现在,我计划渲染角色,以便用户可以看到为他分配了哪些角色。因此,我在最后一个

之前的render部分中添加了此代码块
  <ListItem>
    <Typography>You are assigned the following Roles: </Typography>
  </ListItem>
  {
    this.state.user.roles.map((item, i)=>{
      console.log(item);
      <ListItem key={i}>{item.Module}-{item.Role}</ListItem>
    })
  }
  <Divider/>

我收到此错误:

MyProfile.js?dec7:33 constructor
MyProfile.js?dec7:69 render
MyProfile.js?dec7:33 constructor
MyProfile.js?dec7:69 render
Uncaught TypeError: Cannot read property 'map' of undefined
    at ProxyComponent.render (MyProfile.js?dec7:95)
    at ProxyComponent.hotComponentRender (react-hot-loader.development.js?c2cb:578)
    at ProxyComponent.proxiedRender (react-hot-loader.development.js?c2cb:586)
    at finishClassComponent (react-dom.development.js?61bb:8389)
    at updateClassComponent (react-dom.development.js?61bb:8357)
    at beginWork (react-dom.development.js?61bb:8982)
    at performUnitOfWork (react-dom.development.js?61bb:11814)
    at workLoop (react-dom.development.js?61bb:11843)
    at renderRoot (react-dom.development.js?61bb:11874)
    at performWorkOnRoot (react-dom.development.js?61bb:12449)

我试图通过使用它说的typeof(this.state.user.roles)-对象来查找变量的类型。用Google搜索它,发现它是合适的。我试图将其强制转换为数组,以便可以使用地图,但失败了。 我确定角色状态变量是Array,但是一旦进入render-return(),它就变得不确定。

我想念什么吗?请帮助...整个周末已经在此上了。 :(

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先,安装组件时,this.state.user是不是对象的字符串,因此内部没有任何角色。

最初没有定义角色,因此没有可用于该未定义变量的映射,并且当然根本没有迭代发生...

因此,您应该将其定义为一个空数组,以防止发生错误。

constructor({match}) {
    console.log("constructor");
    super()
    this.state = {
      user: {roles:[]},
      redirectToSignin: false
    };
    this.match = match;
  }

另外,或者,您可以确保在迭代之前没有定义角色。

{
    this.state.user.roles && this.state.user.roles.map((item, i)=>{
      console.log(item);
      <ListItem key={i}>{item.Module}-{item.Role}</ListItem>
    })
  }