从反应中的父路径组件加载状态

时间:2017-01-19 09:12:15

标签: rect

我的反应路由器中存在这种情况:

root.js

<Route path="job-opportunity" component={Opportunity} >
    <Route path=":opportunitySlug" />
</Route>

当我打开domain.com/job-opportunity时,一切正常 但是当我点击子路径domain.com/job-opportunity/some-slug

它没有从我在子组件中使用的Opportunity组件加载一些构造函数状态。

让我告诉你我的机会组件:

class Opportunity extends React.Component{
    constructor(props){
        super(props);

        this.loadOpportunities = this.loadOpportunities.bind(this);

        this.state = {
            'opportunities' : []
        };
        this.loadOpportunities();
    }
    loadOpportunities(){
        $.get($('.api_router_load_opportunities').val(), function(data){
            this.setState({'opportunities' : data});
        }.bind(this));
    }
    render() {
        return (
            <div>
                <h1>Layout!</h1>
                <Content
                    opportunities={this.state.opportunities}
                    loggedUser={this.props.loggedUser}
                    opportunitySlug={this.props.params.opportunitySlug}
                    />
            </div>
        )
    }
} 

function Content(props){
    const opportunitySlug = props.opportunitySlug;
    if(opportunitySlug){
        return <SingleOpportunity
            opportunities={props.opportunities}
            loggedUser={props.loggedUser}
            opportunitySlug={opportunitySlug}
            />;
    }else{
        return <ListOpportunity
            opportunities={props.opportunities}
            loggedUser={props.loggedUser}
            />;
    }
}

导出默认机会;

基本上当我点击domain.com/job-opportunity然后从浏览器中的链接导航时,即使在这条路线中一切正常:

domain.com/job-opportunity/some-slug

但是当我直接点击浏览器domain.com/job-opportunity/some-slug

它破坏了,因为我在SingleOpportunity中渲染this.props.opportunities [this.props.opportunitySlug] .name

1 个答案:

答案 0 :(得分:0)

我找到了一些解决方案:

if(this.props.opportunities.length != 0){
            const opportunity = this.props.opportunities[this.props.opportunitySlug];
            return (
                <div key={this.props.opportunitySlug}>
                    <p><strong>Name:</strong> {opportunity.name}</p>
                    <p><strong>Description:</strong> {opportunity.description}</p>
                </div>
            );
        }else{
            return null;
        }

如果您在初始加载后使用了一些道具或状态,它将呈现多次,并且在最后一次渲染时它将加载您的道具或状态!因此,您需要通过检查状态或道具准备来处理渲染功能。