2017-11-03 3 views
2

내 프로젝트에서 React-Redux Provider를 사용합니다.React-Redux Provider가 작동하지 않습니다.

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 구성 요소에 react-reduxconnect 함수를 사용해야하므로 access to dispatch이됩니다.

export default connect()(Category) 

또한, 단지 SO에 대해 간단하게 할 수 있지만 withRouter에 싸여 할 App 필요가 없습니다. 구성 요소에 라우터 소품을 주입해야하는 경우에만 필요합니다. Route은 렌더링하는 모든 구성 요소에 대해 자동으로이 작업을 수행하므로 Category에 필요하지 않습니다.

export default connect(mapStateToProps)(App)