2017-12-15 11 views
0

당신이 동적 경로를 만들 수 있다는 것을 이해 역동적 인 액션과 동적 경로 :반작용 라우터

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

class PostsContainer extends Component { 
    render() { 
    <p>{this.props.match.params.category}</p> 
    } 
} 

그래서 제 질문은 내가 파견하는 API 호출과 행동에 동적 경로를 추가 할 수있는 방법인가? 카테고리 B의 다음 카테고리 B, 파견에 API 호출을 보내는 동안

나는 ... 범주 A에, 다음, 파견 범주 A에 API 호출을 보낼 때 그런 짓을하고 싶은

export const getPostsAction = (match) => (dispatch) => { 
    getPosts(category).then((posts) => { 
    dispatch({ 
     type: postsConst.GET_ALL_POSTS_SUCCESS, 
     posts, 
    }); 
    }); 
}; 

문제는 this.props.getPostsAction (카테고리)에서 componentDidMount를 사용할 수 없다는 것입니다. 한 번만 발생합니다. 다른 카테고리를 클릭해도 ... 또는 componentWillRecieveProps에서 업데이트해야합니다. 잘 모르는 것이 가장 좋은 방법은 무엇입니까 ...

+0

방법 카테고리 B –

+0

에서 다른 카테고리로 API 호출 당신이 전달하고자하는 작업 유형의 예를 줄 수있다 : 여기

은 설명서에 나와 예를인가? 그것에 대해 역동적 인 것은 무엇입니까? –

+0

님이 그 행동을 추가했습니다. 그래서 getPosts는/api/category/$ {category} –

답변

0

편집 : 귀하의 편집 주소 - 언제든지 componentWillReceiveProps에 귀하의 행동을 보냅니다 this.props.match.params.category !== nextProps.match.params.category.

이렇게하면됩니다. 제공된 postsConst이 제공됩니다. 응용 프로그램이 알고는 현재 데이터를 가져 오는되도록

export const getPostsAction = (match) => (dispatch) => { 
    return getPosts(`/api/category/${match.params.category}`).then(posts => { 
     dispatch({ 
      type: postsConst.GET_ALL_POSTS_SUCCESS, 
      posts, 
     }); 
    }); 
}; 

는 또한 반환 문 앞에 조치를 전달할 수 있습니다. 뭔가 같은 : dispatch({type: "IS_FETCHING_POSTS"}) 물론 당신은 그 행동에 대한 감속기가 필요합니다.

redux에서 비동기 작업에 대한 자세한 내용을 보려면 Async Actions Documentation을 살펴보십시오.

export function fetchPosts(subreddit) { 
    // Thunk middleware knows how to handle functions. 
    // It passes the dispatch method as an argument to the function, 
    // thus making it able to dispatch actions itself. 

    return function (dispatch) { 
    // First dispatch: the app state is updated to inform 
    // that the API call is starting. 

    dispatch(requestPosts(subreddit)) 

    // The function called by the thunk middleware can return a value, 
    // that is passed on as the return value of the dispatch method. 

    // In this case, we return a promise to wait for. 
    // This is not required by thunk middleware, but it is convenient for us. 

    return fetch(`https://www.reddit.com/r/${subreddit}.json`) 
     .then(
     response => response.json(), 
     // Do not use catch, because that will also catch 
     // any errors in the dispatch and resulting render, 
     // causing a loop of 'Unexpected batch number' errors. 
     // https://github.com/facebook/react/issues/6895 
     error => console.log('An error occurred.', error) 
    ) 
     .then(json => 
     // We can dispatch many times! 
     // Here, we update the app state with the results of the API call. 

     dispatch(receivePosts(subreddit, json)) 
    ) 
    } 
}