2016-02-03 33 views
2

假设我有一个组件<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} />其中调用我的MyComponent应返回重定向或其他。

有没有人有任何想法如何实现这一点?

+0

你试过'componentWillReceiveProps(nextProps)'方法吗? –

回答

0

使用check内部渲染方法,你的情况

componentWillMount(){ 
    this.state = { 
    isLoggedIn: this.props.isLoggedIn 
    } 
} 
componentWillReceiveProps(nextProps){ 
this.setState({isLoggedIn: nextProps.isLoggedIn}) 
} 
render(){ 
    return (
    this.props.isLoggedIn && <MyComponent check={this.props} /> 
    ) 
} 
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链接我希望它会帮助你。

谢谢

相关问题