2016-10-17 17 views
0

我有路線:父組件在響應路由器中使用哪種生命週期方法?

<Router history={browserHistory}> 
    <Route path="/" component={Root}> 
    <Route path="/shop" component={Shop}> 
     <Route path="/items" component={AllItems}></Route> 
     <Route path="/collections" component={Collections}></Route> 
    </Route> 
    </Route> 
</Router> 

我父組件店:

export default class Shop extends Component { 
    constructor(props) { 
    super(props) 
    this.state=({ 
     user: cookie.load('user'), 
    }) 
    this.httpHandler = axios.create({ 
     baseURL: 'localhost:3000', 
     headers: { 
     'Authorization': this.state.user.token 
     } 
    }) 
    } 

    componentWillUpdate() { 
    this.httpHandler('/products/') 
    .then(function (response) { 
     console.log('sdfsdf') 
     this.setState({ data: response.data}) 
    }.bind(this)) 
    } 

    render() { 
    var childrenWithProps = React.cloneElement(this.props.children, this.state); 

    return (
     <div> 
     <ShopNav /> 
     {childrenWithProps} 
     </div> 
    ) 
    } 
} 

子組件:

export default class AllItems extends Component { 
    constructor (props) { 
    super(props) 
    console.log(this.props) 
    } 
    render() { 
    return(
       <Child products={this.state.winks} /> 
    )  
    } 
} 

我想使用這個API調用,然後將數據傳遞下來的道具到我的孩子組件。但是,林不知道要使用什麼生命週期事件,我試過了componentWillMount和componentWillUpdate,但它甚至沒有運行api調用。我能夠傳遞this.state.user這個道具,但只是想要一種傳遞數據的方式。我應該以另一種方式接近嗎?

+0

什麼是'this.user'?你的意思是'this.state.user'? – azium

+0

oops yeah this.state.user –

+0

'componentWillMount'應該可以正常工作。我在本地測試了它,沒有任何問題。什麼版本的React和react-router? – joews

回答

0

你試過componentWillReceiveProps(nextProps)? 在它內部,你可以檢查nextProps對象是否與你的狀態相同並更新你的狀態。

我希望這就是你要找的

相關問題