javascript - 将数据推送到我的 Redux 状态
问题描述
现在我正在映射一个带有端点到我的 API 的数组。从那里我获取每一个链接,并对我映射的每一件事调用一个获取请求。我的问题是我无法将所有内容保存到我的 redux 状态。我尝试使用 concat 和 push 来获取所有内容,并将其全部放在我的 redux 状态下的一个数组中。
MomentContent.js:
componentDidMount () {
this.props.photos.map(photo => {
this.props.fetchPhoto(this.props.token, photo)}
)
}
index.js(动作):
export const fetchPhoto = (token, photo) => dispatch => {
console.log('right token')
console.log(token);
fetch(photo, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Token ${token}`,
}
})
.then(res => res.json())
.then(parsedRes => {
console.log('photo data')
console.log(parsedRes)
dispatch(getPhoto(parsedRes))
})
}
export const getPhoto = (photo) => {
console.log('RES')
console.log(photo)
return {
type: GET_PHOTO,
photo: photo
}
}
当我使用 concat (减速器)时:
import {
GET_PHOTO
} from '../actions';
const initialState = {
photo: []
}
const photoReducer = (state = initialState, action) => {
switch(action.type) {
case GET_PHOTO:
return {
...state,
photo: initialState.photo.concat([action.photo])
}
default:
return state;
}
}
export default photoReducer
当我使用推送(减速器)时:
import {
GET_PHOTO
} from '../actions';
const initialState = {
photo: []
}
const photoReducer = (state = initialState, action) => {
switch(action.type) {
case GET_PHOTO:
return {
...state,
photo: initialState.photo.push([action.photo])
}
default:
return state;
}
}
export default photoReducer
更新(另一个问题):
我能够让它工作:
return {
...state,
photo: [...state.photo, action.photo]
}
现在的问题是,每次我刷新相同的数据时都会再次推送,所以一切都会成倍增加。有没有办法解决这个问题?
解决方案
您需要合并您的updatedState
而不是initialState
减速器才能更新
要么使用concat:
return {
...state,
photo: state.photo.concat([action.photo])
}
或使用扩展运算符
return {
...state,
photo: [...state.photo, action.photo]
}
推荐阅读
- sql - 使用 vertica match 子句识别模式的问题
- android - 从通知启动的重复活动
- powershell - 验证 OU 是否存在
- javascript - 逗号后连接字符串与 JavaScript (JSX) 模板文字的正确方法是什么
- python - 如何在一组点中找到最接近另一个点的点?
- python - Pandas:数据框修剪
- javascript - 未触发动作捕捉
- excel - VBA 需要帮助识别与启用宏的按钮关联的活动单元格
- angular - 检查后表达式已更改--> 复选框 mat-tree
- flutter - 在 Flutter 中,子部件如何阻止其可滚动父部件的滚动?