【发布时间】:2017-10-26 15:22:38
【问题描述】:
我正在开发一个基于 react + redux + thunk 的网络应用程序。
我有如下的动作创建者。有 2 个异步 API 调用,首先 fetchUser() 将从服务器获取用户相关信息,然后 fetchUserComments 是另一个异步调用,它返回所有用户 cmets。
export function fetchUserInfoFlow () {
return (dispatch, getState) => {
return dispatch(fetchUser()).then(() => {
return dispatch(fetchUserComments()
})
}
}
export function fetchUser() {
return (dispatch, getState) => {
return axios.get('urlhere')
.then(function (response) {
// basically fetch user data and update the store
dispatch({type: FETCH_USERS, user:response.data)
})
.catch(function (error) {
console.error(error)
})
}
}
export function fetchUserComment() {
return (dispatch, getState) => {
return axios.get('urlhere')
.then(function (response) {
// fetch user comments, get the user list from store, matching the user id and append the comments list to the user
let user = {...getState().user}
response.data.forEach(function (userComment) {
user.forEach(function (userComment) {
if(user.userId = userComment.userId){
user.comments = userComment.comments
}
}
}
dispatch({type: UPDATE_USER_COMMENT, user:response.data)
})
.catch(function (error) {
console.error(error)
})
}
}
我有几个类似于上面的操作创建者获取用户的相关信息并最终更新修改商店的用户列表。
问题是当状态更新时组件没有重新渲染,怀疑我是否在某处改变了用户列表。
我已经阅读了几篇文章,在动作创建者中使用 getSate() 应该只在几种情况下使用,并且不应该更新它的值,因为这会改变状态。
在这种情况下,修改用户列表的逻辑应该放在哪里,如何避免用户列表发生变异?
非常感谢!
【问题讨论】:
标签: redux redux-thunk