2016-10-10 16 views
1

我正在尝试将数据传递给子组件,并且不断收到未定义的道具。我认为当Im在父组件中设置状态时可能会遇到问题。我应该不使用componentWillMount吗?为什么我的道具未定义,当我通过一个已定义的状态?

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

    componentWillMount() { 
    this.httpHandler('/products/') 
    .then(function (response) { 
     this.setState({ winks: response.data.data}) 
     console.log(this.state.winks) 
    }.bind(this)) 
    } 
    render() { 
    return (

       <Winks products={this.state.winks} /> 

    ) 
    } 
} 

回答

3

的问题是,你的承诺可能无法之前componentWillMount结束返回,render被调用。所以products将不存在。你可以做这样的事情:

render() { 
    if (this.state.winks) { 
    return (<Winks products={this.state.winks} />) 
    } else { 
    return (<div>No Winks yet</div>); 
    } 
} 
2

的问题是,你不必为媚眼既然你是依靠一个AJAX调用设置媚眼的状态,Ajax调用将发生异步的初始状态,那么它会在api调用完成之前执行渲染函数,导致this.state.winks最初未定义。

你可以做这样的事情

render() { 
    let content = this.state.winks ? <Winks products={this.state.winks} /> : <div/> 
    return <div> {content} </div>