Chr*_*ard 5 javascript reactjs react-native redux react-redux
现在我正在将一个带有端点的数组映射到我的 API。从那里,我将获取每个链接并在我映射的每个事物上调用 get 请求。我的问题是我无法将所有内容保存到我的 redux 状态。我曾尝试使用 concat 和 push 来获取所有内容,并将其全部放入我的 redux 状态中的一个数组中。
MomentContent.js:
componentDidMount () {
this.props.photos.map(photo => {
this.props.fetchPhoto(this.props.token, photo)}
)
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
当我使用 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
Run Code Online (Sandbox Code Playgroud)
当我使用推送(减速器)时:
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
Run Code Online (Sandbox Code Playgroud)
更新(另一个问题):
我能够让它与:
return {
...state,
photo: [...state.photo, action.photo]
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,每次我刷新相同的数据时都会再次推送,所以一切都会成倍增加。有没有办法来解决这个问题?
您需要将您的updatedState而不是initialState合并到减速器才能更新
使用concat:
return {
...state,
photo: state.photo.concat([action.photo])
}
Run Code Online (Sandbox Code Playgroud)
或使用扩展运算符
return {
...state,
photo: [...state.photo, action.photo]
}
Run Code Online (Sandbox Code Playgroud)