在传入另一个组件之前,确定如何检查道具

时间:2016-02-03 09:52:24

标签: reactjs redux

假设我有一个组件<MyComponent check={this.props} />。这将调用MyComponent类。我在这里做的事情是这样的:

render(){
    const {user} = this.props
    return (){
        <div>Welcome {user.name}</div>
        }
    }

在我的容器中,当用户登录时,最初没有user.name,只有user.name在道具中可用。在componentWillMount我已检查isLoggedIn,如果不是,我重定向,但在render方法中,它会检查登录前无法使用的user.name属性。

如果isLoggedIn为真,则调用<MyComponent check={this.props} />的{​​{1}}应返回重定向或其他。

有谁知道如何实现这个?

2 个答案:

答案 0 :(得分:1)

您可以使用componentWillReceiveProps方法查看道具。它需要nextProps作为参数。

class Parent extends React.Component {
  constructor(props){
     this.state = {
       increment: 0
     }
     this.myClick = this.myClick.bind(this)
  }
  myClick(){
    this.setState({
      increment: this.state.increment + 1
    })
  }
  render(){
    return <div>
      <Child number={this.state.increment}/>
      <button onClick={this.myClick}>Click And Get Props</button>
    </div>
  } 
}

class Child extends React.Component {
   constructor(props){
     console.log(props)
     super(props)
     this.state = {
       count: props.number
     }
   }
   componentWillReceiveProps(nextProps){
     console.log(nextProps.number)
     if(nextProps.number % 2) this.setState({count: nextProps.number})
   }
   render(){
     return <div>
        <span>Props: {this.props.number}</span><br/>
        <span>State: {this.state.count}</span>
     </div>
   }
}

React.render(<Parent />, document.getElementById('container'));

<强> Fiddle Example

另请查看this链接,希望它能为您提供帮助。

由于

答案 1 :(得分:0)

在你的情况下使用check render in render

componentWillMount(){
  this.state = {
   isLoggedIn: this.props.isLoggedIn 
  }
}
componentWillReceiveProps(nextProps){
 this.setState({isLoggedIn: nextProps.isLoggedIn})
}
render(){
  return (
     this.props.isLoggedIn && <MyComponent check={this.props} />
    )
}
相关问题