了解您可以使用以下方法创建动态路线:
<Route path="/:category" component={PostsContainer} />
class PostsContainer extends Component {
render() {
<p>{this.props.match.params.category}</p>
}
}
所以我的问题是如何通过api调用dispatch来为动作添加动态路由?
我想做类似a时的事情,发送api调用类别a,然后发送...而在类别b中发送api调用b类,然后发送...
export const getPostsAction = (match) => (dispatch) => {
getPosts(category).then((posts) => {
dispatch({
type: postsConst.GET_ALL_POSTS_SUCCESS,
posts,
});
});
};
问题是我不能将componentDidMount与this.props.getPostsAction(类别)一起使用,它只发生一次,即使我点击不同/类别......或者我应该从componentWillRecieveProps更新,但我是不确定最好的方式......
答案 0 :(得分:1)
编辑:解决您的修改问题 - 随时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,
});
});
};
您还可以在return语句之前调度操作,以便应用程序知道它当前正在获取数据。类似于: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))
)
}
}