2017-11-03 19 views
2

私のプロジェクトはReact-Redux Providerを使用しています。React-Reduxプロバイダが動作しません

ReactDOM.render(
    <Provider store={store}> 
    <BrowserRouter> 
     <App /> 
    </BrowserRouter> 
    </Provider> 
    , document.getElementById('root')); 

class App extends Component { 

    componentDidMount(){ 

    API.getCategories().then((categories)=>{ 
     this.props.dispatch(addCategories(categories)) 
    }) 

    API.getAllPosts().then(posts => { 
     console.log('getAllPosts', posts) 
    }) 
    } 

    render() { 
    return (
     <div className="App"> 
     <Route exact path="/" render={()=>{ 
      return (
       <div> 
       { 
        this.props.categories.map((category)=>{ 
        return (
          <Link key={category.name} to={`/category/${category.name}`} params={{category: category.name}} >{category.name}</Link> 
        ) 
        }) 
       } 
       </div> 
      ) 
      }} 
     /> 

     <Route path="/category/:category" component={Category} /> 

     </div> 
    ); 
    } 
} 



function mapStateToProps(x) { 

    return { 
    categories: x.categories 
    } 
} 

// export default App; 

export default withRouter(connect(
    mapStateToProps, 
)(App)) 

上記のコードから、前のプロジェクトからの私の経験に基づいて、分類コンポーネントのthis.propsは私がアクションを呼び出すことができdispatch方法を持っているが、いくつかのためにすべきですそれがない理由。

これは私のカテゴリーのコンポーネントです:

class Category extends Component { 
    componentDidMount(){ 
    console.log('this.props of Category', this.props) 

    var category = this.props.match.params.category 

    API.getPosts(category).then((posts)=>{ 
     console.log('after getPosts', posts) 
     this.props.dispatch(addAllPosts(posts)) 
    }) 
    } 

    render(){ 
    return <p>Category</p> 
    } 
} 

export default Category 

私はここで何をしないのです?

+0

プロバイダ要素をラップするだけでは不十分です。州をプロップにマップし、ディスパッチ機能を渡すカテゴリコンポーネントの周りにコンテナコンポーネントを作成する必要があります。ドキュメント:http://redux.js.org/docs/basics/UsageWithReact.htmlを参照してください。 –

答えて

2

Categoryコンポーネントのconnect機能をreact-reduxから使用する必要がありますので、access to dispatchがあります。

export default connect()(Category) 

はまた、それだけでSOのために簡略化されるかもしれないが、withRouterに包まれたことをApp必要はありません。これは、ルータのプロップをコンポーネントに注入する必要がある場合にのみ必要です。 Routeはレンダリングするすべてのコンポーネントに対してこれを自動的に行います。そのため、Categoryに必要ではありません。

export default connect(mapStateToProps)(App) 
関連する問題