2016-08-01 81 views
2

我有一个非常简单的React.js组件,我需要做一个isomorphic(呈现在服务器上)。问题是有帮助的信息后,才ajax请求完成,这样渲染该组件:react.js不渲染,直到ajax请求完成

export default React.createClass({ 
    getInitialState() { 
    return {} 
    }, 

    componentDidMount() { 
    fetch("https://stackoverflow.com/users/").then(response => { 
     this.setState(users: response.data) 
    }) 
    }, 

    render() { 
    if (this.state.users == undefined) { 
     return <div /> 
    } 

    return <div>{this.state.users.map(some_function)}</div> 
    } 
}) 

的问题是,这是毫无意义空车返回div搜索引擎。我想要ajax请求完成(即使在服务器上)并仅在此之后呈现。我怎样才能做到这一点?

+0

我相信你想采取父组件,并使用道具而不是状态,让父组件决定是否渲染它。 – Dencker

+0

@Dencker您能解释一下如何决定是否渲染它吗? – asiniy

回答

4

正如@Dencker谈到了,你想父组件决定何时渲染子组件,像这样的工作:

// Parent 
export default React.createClass({ 
    getInitialState() { 
    return { 
     usersLoaded: false 
    } 
    }, 

    componentDidMount() { 
    fetch("https://stackoverflow.com/users/").then(response => { 
     this._users = response.users; 
     this.setState({ 
     usersLoaded: true 
     }); 
    }) 
    }, 

    render() { 
    if (this.state.usersLoaded) { 
     return (
     <ChildComponent users={this._users} /> 
    ) 
    } else { 
     return null; 
    } 
    } 
}); 

// Child 
export default React.createClass({ 
    render() { 
    return <div>{this.props.users.map(some_function)}</div> 
    } 
}); 

我在做什么有:

  1. 在父组件上设置初始状态,即usersLoaded: false
  2. 在该组件的渲染函数中,确保当父项的usersLoaded状态为true时,仅显示子组件。
  3. 父组件的componentDidMount方法是发生AJAX调用的方法,并且注意我使用组件上的一个变量来存储用户,状态对象(状态通常只应用于存储非常简单的值)而不是
  4. 然后传递给子组件作为道具。

以上所有使得子组件更简单,因为它现在只需要一个渲染方法,并且没有if/else检查。

+0

我遵循这种方法,但服务器返回给我一个'' – asiniy

+0

问题是你如何编写测试,所以它会等到渲染不是“空”。 – ram4nd