首页 > 解决方案 > 不确定我对 React Redux 应用程序中特定部分的处理方法?

问题描述

我正在开发一个迷你 React Redux 应用程序,最初我正在加载文章列表。单击这些文章中的每一个都应在页面上呈现该特定文章的内容和详细信息。

我当前的应用架构如下

应用程序.js

class App extends Component {
    render() {
        return (
            <div className="App">
                <AppHeader></AppHeader>
                <PageContent></PageContent>
            </div>
        );
    }
}

PageContentContainer.js

const mapStateToProps = state => ({
    posts: state.simpleReducer.posts
});

const mapDispatchToProps = dispatch => {

    return {
        frontPagePosts: () => {
            dispatch(actions.frontPageItems())
        }
    }
};


class PageContentContainer extends Component{

    componentDidMount(){
        this.props.frontPagePosts();
    }

    render(){
        return(
            <div>
                <main>
                    <FrontPageComponent posts={this.props.posts}/>
                </main>
            </div>
        )
    }
}

FrontPageComponent只是一个视图渲染组件,其中没有任何逻辑。

class FrontPageComponent extends Component{
    render(){

        return(
            <div>
                <div className="container frontPageContainer">
                    {this.props.posts.map((val, idx) => {
                        return(
                            <div key={idx} className='row frontPageContent'>
                                <div className="col-12 col-md-12 col-sm-12 col-lg-12">
                                    <h2>
                                        <a href={'/' + val.slug}>
                                            {val.title}
                                        </a>
                                    </h2>
                                </div>
                                <div className="col-12 col-md-12 col-sm-12 col-lg-12">{val.excerpt}</div>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }
} 

我目前的想法是引入另一个视图组件来查看单个文章<ReadArticleComponent/>。每次用户单击单个文章时,它都会更改showArticle商店中调用的布尔状态值。基于此,它将相应地渲染任一组件。因此,例如,我的 PageContentContainer 中的逻辑看起来像

componentDidMount(){
    //ajax call to the backend

    if(!this.props.showArticle){
     this.props.frontPagePosts();
    }else{
      this.props.showArticleContent()
    } 
}

.........

render(){
   ......

   {!this.props.showArticle ? <FrontPageComponent.../> 
     : <ReadArticleComponent/>
   }
}

但是我将如何处理用户点击后退按钮并返回包含所有文章的页面的情况。我的方法是正确的还是应该在我的应用程序中使用 React Router?

标签: javascriptreactjsredux

解决方案


推荐阅读