【发布时间】:2019-01-18 10:55:53
【问题描述】:
现在我正在映射一个带有端点的数组到我的 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 (reducer) 时:
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
当我使用 push(reducer)时:
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]
}
现在的问题是,每次我刷新相同的数据时都会再次推送,所以一切都会成倍增加。有没有办法来解决这个问题?
【问题讨论】:
标签: javascript reactjs react-native redux react-redux