如果满足条件如何继续安装?

时间:2018-07-10 05:42:53

标签: reactjs

我正在使用react,并且有一个看起来像这样的componentWillMount

componentWillMount() {
  axios.get('/user').then(response => {
    console.log(response.data.user)
    if (response.data.user) {
    } else {
      this.props.history.replace('/signup');
    }
  });
}

请在代码中将此行注意。

if (response.data.user) {
        } 

现在,如果满足条件,如何使容器呈现?

2 个答案:

答案 0 :(得分:1)

user方法中接收到then变量后,只需将其设置为组件状态,以后便可以在渲染方法中使用它:

import React from 'react'

class App extends React.Component { 
  constructor (props) {
    super(props)

    this.state = { user: null }
  }

  componentWillMount() {
    axios.get('/user').then(response => {

      if (response.data.user) {
        this.setState({ user: reaponse.data.user )}
      } else {
        this.props.history.replace('/signup')
      }
    })
  }

  render() {
    // Do something with the user
    if (this.state.user) {
      return <div>{this.state.user.name}</div>
    }

    return <div />
  }
}

答案 1 :(得分:0)

嗨,请根据状态进行有条件的渲染。

import React from "react";

class ExampleComponent extends React.PureComponent {
  state={ user: null }

  static getDerivedStateFromProps(nextProps, prevState){
    if(!prevState.user && state.user){
      this.props.history.replace('/signup');
    }

   else return null;
  }

  componentWillMount() {
      axios.get('/user').then(response => {
        console.log(response.data.user)
        if (response.data.user) {
           this.setState({ user: response.data.user )}
        }
     });
  }

  render() {
    const { user } = this.state;
    return user ? <div>have user, can return null</div> : <div>loading user</div>
  }
}

export default ExampleComponent;