首页 > 解决方案 > 将数据推送到我的 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]
      }

现在的问题是,每次我刷新相同的数据时都会再次推送,所以一切都会成倍增加。有没有办法解决这个问题?

标签: javascriptreactjsreact-nativereduxreact-redux

解决方案


您需要合并您的updatedState而不是initialState减速器才能更新

要么使用concat

return {
  ...state,
  photo: state.photo.concat([action.photo])
}

使用扩展运算符

return {
  ...state,
  photo: [...state.photo, action.photo]
}

推荐阅读